If you want to perform fast linear regressions in Swift, I suggest using Upsurge . It provides a number of simple functions that wrap the acceleration library, and so you get the benefits of SIMD on iOS or OSX without having to worry about the complexity of vDSP calls.
For linear regression with basic Upsurge functions, simply:
let meanx = mean (x)
let meany = mean (y)
let meanxy = mean (x * y)
let meanx_sqr = measq (x)
let slope = (meanx * meany - meanxy) / (meanx * meanx - meanx_sqr)
let intercept = meany - slope * meanx
This is essentially what is implemented in the linregress function.
You can use it with the [Double] array, other classes such as RealArray (supplied with Upsurge), or your own objects if they can expose continuous memory.
So, a script to meet your needs would look like this:
#! / usr / bin / env cato
import upsurge
typealias PointTuple = (day: Double, mW: Double)
var myArray: [PointTuple] = []
myArray.append ((0, 31.98))
myArray.append ((1, 31.89))
myArray.append ((2, 31.77))
myArray.append ((4, 31.58))
myArray.append ((6, 31.46))
let x = myArray.map {$ 0.day}
let y = myArray.map {$ 0.mW}
let (slope, intercept) = Upsurge.linregress (x, y)
func bG (day: Double) -> Double {
return slope * day + intercept
}
(I left the attachments, and did not use literals, since you probably programmatically add your array if it is of considerable length)
and full disclaimer: I entered the linregress code. Hopefully at some point in the future we will also add a definition factor.
timbo source share