-
Notifications
You must be signed in to change notification settings - Fork 224
/
sample_kurtosis.js
44 lines (38 loc) · 1.36 KB
/
sample_kurtosis.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
42
43
44
import mean from "./mean";
/**
* [Kurtosis](http://en.wikipedia.org/wiki/Kurtosis) is
* a measure of the heaviness of a distribution's tails relative to its
* variance. The kurtosis value can be positive or negative, or even undefined.
*
* Implementation is based on Fisher's excess kurtosis definition and uses
* unbiased moment estimators. This is the version found in Excel and available
* in several statistical packages, including SAS and SciPy.
*
* @param {Array<number>} x a sample of 4 or more data points
* @returns {number} sample kurtosis
* @throws {Error} if x has length less than 4
* @example
* sampleKurtosis([1, 2, 2, 3, 5]); // => 1.4555765595463122
*/
function sampleKurtosis(x) {
const n = x.length;
if (n < 4) {
throw new Error("sampleKurtosis requires at least four data points");
}
const meanValue = mean(x);
let tempValue;
let secondCentralMoment = 0;
let fourthCentralMoment = 0;
for (let i = 0; i < n; i++) {
tempValue = x[i] - meanValue;
secondCentralMoment += tempValue * tempValue;
fourthCentralMoment += tempValue * tempValue * tempValue * tempValue;
}
return (
((n - 1) / ((n - 2) * (n - 3))) *
((n * (n + 1) * fourthCentralMoment) /
(secondCentralMoment * secondCentralMoment) -
3 * (n - 1))
);
}
export default sampleKurtosis;