als-statistics
Version:
A powerful and lightweight JavaScript library for descriptive statistics, regression, clustering, outlier detection, and noise analysis using a flexible table/column architecture.
24 lines (20 loc) • 1.14 kB
JavaScript
function confidenceInterval(sample) {
const tTable95 = {
1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571,
6: 2.447, 7: 2.365, 8: 2.306, 9: 2.262, 10: 2.228,
11: 2.201, 12: 2.179, 13: 2.160, 14: 2.145, 15: 2.131,
16: 2.120, 17: 2.110, 18: 2.101, 19: 2.093, 20: 2.086,
21: 2.080, 22: 2.074, 23: 2.069, 24: 2.064, 25: 2.060,
26: 2.056, 27: 2.052, 28: 2.048, 29: 2.045, 30: 2.042
};
const { n, mean, stdDevSample } = sample;
if (n < 2) return { low: mean, high: mean, width: 0 };
const df = n - 1;
let criticalValue = df <= 30 ? tTable95[df] : 1.96;
const margin = criticalValue * (stdDevSample / Math.sqrt(n)); // Если стандартное отклонение равно 0, margin будет равен 0
const low = mean - margin;
const high = mean + margin;
const width = mean !== 0 ? ((high - low) / Math.abs(mean)) * 100 : (high - low); // Если mean равен 0, нельзя вычислять относительную ширину делением на mean.
return { low, high, width };
}
module.exports = confidenceInterval