Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Accelerate for Mean & Standard Deviation

I am looking at Accelerate to compute mean and standard deviation of arrays in Swift.

I can do the mean. How do I do the standard deviation?

let rr: [Double] = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]

var mn: Double = 0.0

vDSP_meanvD(rr, 1, &mn, vDSP_Length(rr.count))

print(mn) // prints correct mean as 45.6250

// Standard Deviation should be 22.3155
like image 342
Pat Avatar asked Feb 09 '17 09:02

Pat


People also ask

What is Apple accelerate?

Accelerate performs optimized large-scale mathematical computations and image calculations so you can write apps that leverage machine learning, data compression, signal processing, and more.

What is accelerate framework?

The Accelerate Framework is the core methodology that serves as the foundation of Accelerate Institute's work closing the achievement gap. By moving through the Framework objectives, educators from around the country implement the proven approach for driving ongoing results at their schools.


1 Answers

You can compute the standard deviation from the mean value and the mean square value (compare https://en.wikipedia.org/wiki/Standard_deviation#Identities_and_mathematical_properties and https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance):

import Accelerate

let rr: [Double] = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]

var mn: Double = 0.0 // mean value
vDSP_meanvD(rr, 1, &mn, vDSP_Length(rr.count))

var ms: Double = 0.0 // mean square value
vDSP_measqvD(rr, 1, &ms, vDSP_Length(rr.count))

let sddev = sqrt(ms - mn * mn) * sqrt(Double(rr.count)/Double(rr.count - 1))

print(mn, sddev)
// 45.625 22.315513501982

Alternatively (for iOS 9.0 and later or macOS 10.11 and later), use vDSP_normalizeD:

var mn = 0.0
var sddev = 0.0
vDSP_normalizeD(rr, 1, nil, 1, &mn, &sddev, vDSP_Length(rr.count))
sddev *= sqrt(Double(rr.count)/Double(rr.count - 1))

print(mn, sddev)
// 45.625 22.315513501982
like image 59
Martin R Avatar answered Oct 11 '22 08:10

Martin R