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 |
almost oneliner from java(rxjava actually) :
private Double standardDeviation(List<Double> array) {
final double length = array.size();
final double average = sumOf(array) / length;
double standardDeviation = Observable.fromIterable(array)
.map(new Function<Double, Double>() {
@Override
public Double apply(Double $0) throws Exception {
return Math.pow($0 - average, 2.0);
}
})
.toList()
.map(new Function<List<Double>, Double>() {
@Override
public Double apply(List<Double> $0) throws Exception {
return sumOf($0);
}
})
.map(new Function<Double, Double>() {
@Override
public Double apply(Double result) throws Exception {
return Math.sqrt(result / length);
}
})
.blockingGet();
return standardDeviation;
}
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))
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
Inspired by http://www.jefclaes.be/2015/01/averages-are-not-good-enough-f.html