Last active
December 7, 2023 10:48
-
-
Save denpazakura/b5c08dddbcecb88aa45ab56802d28400 to your computer and use it in GitHub Desktop.
Calculating variance in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculating variance in Swift | |
let data = [0, 1, 5, 7, 9, 10, 14] | |
func variance<T: BinaryFloatingPoint>(input: Array<T>) -> T { | |
let sum = input.reduce(0, +) | |
let mean = sum / T(input.count) | |
let sumOfSquaredDifferences = input.reduce(0) { $0 + (mean - $1) * (mean - $1) } | |
let variance = sumOfSquaredDifferences / T(input.count) | |
return variance | |
} | |
func standardDeviation<T: BinaryFloatingPoint>(input: Array<T>) -> Double { | |
return sqrt(Double(variance(input: input))) | |
} | |
print(variance(input: data.map{Double($0)})) | |
print(standardDeviation(input: data.map{Double($0)})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment