Skip to content

Instantly share code, notes, and snippets.

@denpazakura
Last active December 7, 2023 10:48
Show Gist options
  • Save denpazakura/b5c08dddbcecb88aa45ab56802d28400 to your computer and use it in GitHub Desktop.
Save denpazakura/b5c08dddbcecb88aa45ab56802d28400 to your computer and use it in GitHub Desktop.
Calculating variance in Swift
# 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