find the standard deviation of all elements in an array in swift

To find the standard deviation of all elements in an array in Swift, first, calculate the mean of the array. Then, for each element, subtract the mean, square the result, and add it to a running sum. Finally, divide the sum by the number of elements minus one, and take the square root of the result.

Here's an example implementation:

main.swift
func standardDeviation(_ arr: [Double]) -> Double? {
    let count = arr.count
    guard count > 1 else { return nil } // there must be at least 2 elements to calculate the standard deviation
    
    let sum = arr.reduce(0, +)
    let mean = sum / Double(count)
    
    let squaredDifferencesSum = arr.reduce(0) { result, element in
        let difference = element - mean
        return result + difference * difference
    }
    
    return sqrt(squaredDifferencesSum / Double(count - 1))
}

let arr = [1.0, 2.0, 3.0, 4.0, 5.0]
if let sd = standardDeviation(arr) {
    print("Standard deviation of \(arr) is \(sd)") // Standard deviation of [1.0, 2.0, 3.0, 4.0, 5.0] is 1.5811388300841898
} else {
    print("Array must have at least 2 elements")
}
753 chars
22 lines

gistlibby LogSnag