Swift Accelerate for Mean & Standard Deviation

情到浓时终转凉″ 提交于 2019-12-10 19:46:42

问题


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

回答1:


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



回答2:


an add-on for @Martin R's answer: There is also a vDSP_normalize function for Float/single precision.

func vDSP_normalize(UnsafePointer<Float>, vDSP_Stride, UnsafeMutablePointer<Float>?, vDSP_Stride, UnsafeMutablePointer<Float>, UnsafeMutablePointer<Float>, vDSP_Length)
//Compute mean and standard deviation and then calculate new elements to have a zero mean and a unit standard deviation. Single precision.

func vDSP_normalizeD(UnsafePointer<Double>, vDSP_Stride, UnsafeMutablePointer<Double>?, vDSP_Stride, UnsafeMutablePointer<Double>, UnsafeMutablePointer<Double>, vDSP_Length)
//Compute mean and standard deviation and then calculate new elements to have a zero mean and a unit standard deviation. Double precision.


来源:https://stackoverflow.com/questions/42133107/swift-accelerate-for-mean-standard-deviation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!