find the standard deviation of a list of numbers in swift

To find the standard deviation of a list of numbers in Swift, you can use the sqrt and reduce functions provided by the Swift Standard Library in conjunction with some mathematical formulas. Here's an example implementation:

main.swift
extension Array where Element == Double {
  var standardDeviation: Double? {
    guard count > 1 else { return nil }
    
    let mean = reduce(0, +) / Double(count)
    let variance = map { pow($0 - mean, 2.0) }.reduce(0, +) / Double(count - 1)
    
    return sqrt(variance)
  }
}
283 chars
11 lines

This implementation defines a computed property called standardDeviation on an array of Double values. It first checks that the array has at least two elements (otherwise, the standard deviation is undefined), and then calculates the mean of the values using the reduce function.

Once we have the mean, we can calculate the variance of the values using the formula:

main.swift
variance = sum((x - mean)^2) / (n - 1)
39 chars
2 lines

where n is the number of elements in the array. We use the map and reduce functions to perform this calculation.

Finally, we return the square root of the variance to get the standard deviation.

Here's an example usage:

main.swift
let numbers = [1.0, 2.0, 3.0, 4.0, 5.0]
if let stdDev = numbers.standardDeviation {
  print("The standard deviation is: \(stdDev)") // Output: The standard deviation is: 1.5811388300841898
}
191 chars
5 lines

Note that this implementation assumes that the list of numbers is a simple array of Double values. If your input data is in a different format (e.g. a dictionary or a custom object), you may need to modify the implementation accordingly.

gistlibby LogSnag