Last active
February 15, 2024 21:45
-
-
Save jonelf/9ae2a2133e21e255e692 to your computer and use it in GitHub Desktop.
Standard Deviation 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
func standardDeviation(arr : [Double]) -> Double | |
{ | |
let length = Double(arr.count) | |
let avg = arr.reduce(0, {$0 + $1}) / length | |
let sumOfSquaredAvgDiff = arr.map { pow($0 - avg, 2.0)}.reduce(0, {$0 + $1}) | |
return sqrt(sumOfSquaredAvgDiff / length) | |
} | |
let responseTimes = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ] | |
standardDeviation(responseTimes) // 20.8742514835862 | |
standardDeviation([2,4,4,4,5,5,7,9]) // 2.0 |
also, I think .reduce(0, {$0 + $1})
can be simplified to .reduce(0, +)
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
stddev([ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]) => 22.315514
stddev([2,4,4,4,5,5,7,9]) => 2.1380899
It should be
sqrt(sumOfSquaredAvgDiff / (length - 1))