liveBook · Manning

Mean

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

A mean is a measure of central tendency, calculated as the arithmetic average of values or, for a random variable, as the probability-weighted average of its possible values.

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

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

How deep it goes
Defines the mean as sum divided by count and implements it as an Array<Double> property, without teaching elementary statistics.
Examples
Uses a five-value dataset yielding 394 and averages assigned point coordinates to recalculate centroids.
What it assumes
Assumes rudimentary familiarity with mean and standard deviation, while leaving elementary statistics instruction out.
What you can do after
Build a Swift Array<Double> mean property by dividing the sum by the element count.
How it connects
Connects mean to sum, variance, standard deviation, z-scores, and k-means centroids.

Also explained in

Compare how 29 books explain mean →

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.