To find the variance of all elements in an array in Swift, you can use the following code block:
main.swift180 chars5 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.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