find the variance of all elements in an array in swift

To find the variance of all elements in an array in Swift, you can use the following code block:

main.swift
let arr = [3, 4, 5, 6, 7]
let mean = arr.reduce(0, +) / arr.count
let variance = arr.map { pow(Double($0) - Double(mean), 2) }.reduce(0, +) / Double(arr.count - 1)
print(variance)
180 chars
5 lines

Explanation:

  • arr is the array for which we want the variance. In this example, it is [3, 4, 5, 6, 7].
  • mean is the mean of the array elements. First, we use reduce to find the sum of all elements in the array. Then, we divide the sum by the count of the array to get the mean.
  • Next, we calculate the variance. We use map to create a new array where each element is the square of the difference between the element and the mean. Then, we use reduce to find the sum of all elements in this new array. Finally, we divide the sum by arr.count - 1 to get the variance.

The output of the above code block will be 2.5, which is the variance of the elements in the array [3, 4, 5, 6, 7].

gistlibby LogSnag