sample_kurtosis.js

import mean from "./mean.js";

/**
 * [峰度](http://en.wikipedia.org/wiki/Kurtosis) 是
 * 衡量分布尾部相对于其方差的厚度的指标。峰度值可以是正数、负数,甚至未定义。
 *
 * 实现基于 Fisher 的超额峰度定义,并使用无偏矩估计。这是 Excel 中使用的版本,
 * 并在多个统计软件包中可用,包括 SAS 和 SciPy。
 *
 * @param {Array<number>} x 包含 4 个或更多数据点的样本
 * @returns {number} 样本峰度
 * @throws {Error} 如果 x 的长度小于 4
 * @example
 * sampleKurtosis([1, 2, 2, 3, 5]); // => 1.4555765595463122
 */
function sampleKurtosis(x) {
    const n = x.length;

    if (n < 4) {
        throw new Error("sampleKurtosis 至少需要四个数据点");
    }

    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;