The mean, or average, is the sum of a set of values divided by their count. For an array of Doubles, calculate it by dividing the array’s sum by its element count. 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
}
}
A Swift Array<Double> extension builds mean from sum and count; the same extension also defines variance, standard deviation, and z-scores. section 6.1
A small dataset
For [600, 470, 170, 430, 300], the mean is 394. In k-means, the same calculation finds each cluster centroid’s coordinate values. section 6.1 section 6.2




























