liveBook · Manning

Variance

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Variance is a statistical measure of the average squared deviation of values from their mean.

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

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines and implements the formula for arrays of Doubles, but defers elementary statistics beyond rudimentary mean and standard deviation.
Examples
Calculates variance for [600, 470, 170, 430, 300], yielding 21,704.
What it assumes
Assumes rudimentary mean and standard deviation knowledge while defining the implementation from the statistical formula.
What you can do after
Build it from scratch as a computed Array<Double> property and test it with sample data.
How it connects
Connects variance to mean, standard deviation, z-scores, and K-means clustering.

Also explained in

Compare how 19 books explain variance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.