Skip to main content
Module

x/simplestatistics/src/sum_nth_power_deviations.js

simple statistics for node & browser javascript
Go to Latest
File
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;