find the variance of a list of numbers in swift

To find the variance of a list of numbers in Swift, you can use the following code:

main.swift
func variance(_ numbers: [Double]) -> Double? {
    guard numbers.count > 1 else { return nil }

    let mean = numbers.reduce(0, +) / Double(numbers.count)
    let variance = numbers.reduce(0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count - 1)

    return variance
}
280 chars
9 lines

Here, we define a function variance that takes an array of Double values as input. The function first checks if the array has at least two elements, without which it is not possible to calculate variance. If there is only one element, the function returns nil.

Next, we calculate the mean of the array by adding up all the numbers and dividing by the count. We then iterate over the array, subtract the mean from each number, square the result, and add it to a running total. Finally, we divide the total by the count minus one to get the variance.

Note that we subtract one from the count in the denominator because we are estimating the variance of a population from a sample, so we have one less degree of freedom. If you are calculating the variance of a full population, you should use the full count instead.

Example usage:

main.swift
let data = [1.0, 2.0, 3.0, 4.0, 5.0]
if let result = variance(data) {
    print("Variance: \(result)") // Output: Variance: 2.5
}
130 chars
5 lines

Here, we define an array data with some example data, and pass it to the variance function. If the function returns a non-nil result, we print it to the console. In this case, the output is Variance: 2.5.

gistlibby LogSnag