Variance measures the average squared distance of values from their mean. For an array of Doubles, calculate the mean, square each deviation, then average those squared deviations. section 6.1
A small worked calculation
For [600, 470, 170, 430, 300], the mean is 394 and the variance is 21,704. Standard deviation then derives from variance by taking its square root, producing 147. section 6.1
import Foundation // for pow(), srand48(), drand48()
extension Array where Element == Double {
var sum: Double {
return self.reduce(0.0, +)
}
// Find the average (mean)
var mean: Double {
return sum / Double(self.count)
}
// Find the variance sum((Xi - mean)^2) / N
var variance: Double {
let mean = self.mean // cache so not recalculated for every element
return self.map { pow(($0 - mean), 2) }.mean
}
// Find the standard deviation sqrt(variance)
var std: Double {
return sqrt(variance)
}
// Convert elements to respective z-scores (formula z-score =
(x - mean) / std)
var zscored: [Double] {
let mean = self.mean
let std = self.std
return self.map{ std != 0 ? (($0 -
mean) / std) : 0.0 } // avoid divide by zero
}
}
Use the Array extension to implement variance from mean, while caching the mean so it is not recalculated for every element. section 6.1


















