"Variance" is commonly used in statistics and probability theory.
Given a sequence of numbers, how to find their variance?
First, find their average, then subtract the average from each number, find their sum of squares, and finally divide by the size of the sequence to get the variance.
For example: Given a sequence, [1, 2, 2, 3].
First find the average:
(1 + 2 + 2 + 3) / 4 => 2
Then find the variance:
((( 1 - 2)^2 + (2 - 2)^2 + (2-2)^2 + (3 - 2)^2) / 4 => 0.5
Sometimes, this result will be For very long decimals, we don't need to find so many digits, just keep 3 or 4 decimal digits. At this time, we can use the toFixed method of JS to round the decimals.
var variance = function(numbers) { var mean = 0; var sum = 0; for(var i=0;i<numbers.length;i++){ sum += numbers[i]; } mean = sum / numbers.length; sum = 0; for(var i=0;i<numbers.length;i++){ sum += Math.pow(numbers[i] - mean , 2); } return sum / numbers.length; };
The above is an interesting JavaScript question: calculating the variance. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!