t_test_two_sample.js

import mean from "./mean.js";
import sampleVariance from "./sample_variance.js";

/**
 * 本函数用于计算[双样本t检验](http://en.wikipedia.org/wiki/Student's_t-test)
 * 检验"mean(X)-mean(Y) = difference"的假设(最常见情况是当`difference == 0`时,
 * 检验两个样本是否可能来自具有相同均值的总体),在未知两样本标准差但假设它们具有相同标准差时使用。
 *
 * 通常计算结果用于查找[P值](http://en.wikipedia.org/wiki/P-value),
 * 根据给定的显著性水平判断是否可以拒绝零假设。
 *
 * 当差值为0时,`diff`参数可省略。
 *
 * [本检验用于拒绝](https://en.wikipedia.org/wiki/Exclusion_of_the_null_hypothesis)
 * 样本X和样本Y来自相同总体均值的零假设。
 *
 * @param {Array<number>} sampleX 样本数据,以数字数组表示
 * @param {Array<number>} sampleY 样本数据,以数字数组表示
 * @param {number} [difference=0] 期望均值差
 * @returns {number|null} 检验统计量
 *
 * @example
 * tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0); // => -2.1908902300206643
 */
function tTestTwoSample(sampleX, sampleY, difference) {
    const n = sampleX.length;
    const m = sampleY.length;

    // 如果任一样本没有数据,无法计算,返回null
    if (!n || !m) {
        return null;
    }

    // 默认差值(mu)为0
    if (!difference) {
        difference = 0;
    }

    const meanX = mean(sampleX);
    const meanY = mean(sampleY);
    const sampleVarianceX = sampleVariance(sampleX);
    const sampleVarianceY = sampleVariance(sampleY);

    if (
        typeof meanX === "number" &&
        typeof meanY === "number" &&
        typeof sampleVarianceX === "number" &&
        typeof sampleVarianceY === "number"
    ) {
        // 计算合并方差
        const weightedVariance =
            ((n - 1) * sampleVarianceX + (m - 1) * sampleVarianceY) /
            (n + m - 2);

        // 返回t统计量
        return (
            (meanX - meanY - difference) /
            Math.sqrt(weightedVariance * (1 / n + 1 / m))
        );
    }
}

export default tTestTwoSample;