-
Notifications
You must be signed in to change notification settings - Fork 224
/
sum_nth_power_deviations.js
41 lines (37 loc) · 1.1 KB
/
sum_nth_power_deviations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import mean from "./mean.js";
/**
* The sum of deviations to the Nth power.
* When n=2 it's the sum of squared deviations.
* When n=3 it's the sum of cubed deviations.
*
* @param {Array<number>} x
* @param {number} n power
* @returns {number} sum of nth power deviations
*
* @example
* var input = [1, 2, 3];
* // since the variance of a set is the mean squared
* // deviations, we can calculate that with sumNthPowerDeviations:
* sumNthPowerDeviations(input, 2) / input.length;
*/
function sumNthPowerDeviations(x, n) {
const meanValue = mean(x);
let sum = 0;
let tempValue;
let i;
// This is an optimization: when n is 2 (we're computing a number squared),
// multiplying the number by itself is significantly faster than using
// the Math.pow method.
if (n === 2) {
for (i = 0; i < x.length; i++) {
tempValue = x[i] - meanValue;
sum += tempValue * tempValue;
}
} else {
for (i = 0; i < x.length; i++) {
sum += Math.pow(x[i] - meanValue, n);
}
}
return sum;
}
export default sumNthPowerDeviations;