sample_skewness.js

import mean from "./mean.js";

/**
 * [偏度](http://en.wikipedia.org/wiki/Skewness) 是衡量实值随机变量的概率分布
 * 在均值一侧“倾斜”程度的统计量。
 * 偏度的值可以为正、负,甚至未定义。
 *
 * 该实现基于调整后的 Fisher-Pearson 标准化矩系数,
 * 该方法被 Excel 及多个统计软件(如 Minitab、SAS 和 SPSS)采用。
 *
 * @since 4.1.0
 * @param {Array<number>} x 至少包含 3 个数据点的样本数据
 * @returns {number} 样本偏度
 * @throws {Error} 如果 x 的长度小于 3
 * @example
 * sampleSkewness([2, 4, 6, 3, 1]); // => 0.590128656384365
 */
function sampleSkewness(x) {
    if (x.length < 3) {
        throw new Error("sampleSkewness 需要至少包含三个数据点");
    }

    const meanValue = mean(x);
    let tempValue;
    let sumSquaredDeviations = 0;
    let sumCubedDeviations = 0;

    for (let i = 0; i < x.length; i++) {
        tempValue = x[i] - meanValue;
        sumSquaredDeviations += tempValue * tempValue;
        sumCubedDeviations += tempValue * tempValue * tempValue;
    }

    // 贝塞尔校正(Bessel's Correction):对样本统计量进行调整,
    // 以补偿由于使用样本数据而导致的自由度减少。
    const besselsCorrection = x.length - 1;

    // 计算样本标准差
    const theSampleStandardDeviation = Math.sqrt(
        sumSquaredDeviations / besselsCorrection
    );

    const n = x.length;
    const cubedS = Math.pow(theSampleStandardDeviation, 3);

    // 计算并返回样本偏度
    return (n * sumCubedDeviations) / ((n - 1) * (n - 2) * cubedS);
}

export default sampleSkewness;