Skip to content

Instantly share code, notes, and snippets.

@jonelf
Last active February 15, 2024 21:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonelf/9ae2a2133e21e255e692 to your computer and use it in GitHub Desktop.
Save jonelf/9ae2a2133e21e255e692 to your computer and use it in GitHub Desktop.
Standard Deviation in Swift
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
@jonelf
Copy link
Author

jonelf commented Jan 19, 2015

@Marchuck
Copy link

Marchuck commented Jun 1, 2017

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;
}

@patrick-zippenfenig
Copy link

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))

@sbromberger
Copy link

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