UNPKG

1.22 kBJavaScriptView Raw
1import mean from "./mean";
2import standardDeviation from "./standard_deviation";
3
4/**
5 * This is to compute [a one-sample t-test](https://en.wikipedia.org/wiki/Student%27s_t-test#One-sample_t-test), comparing the mean
6 * of a sample to a known value, x.
7 *
8 * in this case, we're trying to determine whether the
9 * population mean is equal to the value that we know, which is `x`
10 * here. usually the results here are used to look up a
11 * [p-value](http://en.wikipedia.org/wiki/P-value), which, for
12 * a certain level of significance, will let you determine that the
13 * null hypothesis can or cannot be rejected.
14 *
15 * @param {Array<number>} x sample of one or more numbers
16 * @param {number} expectedValue expected value of the population mean
17 * @returns {number} value
18 * @example
19 * tTest([1, 2, 3, 4, 5, 6], 3.385).toFixed(2); // => '0.16'
20 */
21function tTest(x, expectedValue) {
22 // The mean of the sample
23 const sampleMean = mean(x);
24
25 // The standard deviation of the sample
26 const sd = standardDeviation(x);
27
28 // Square root the length of the sample
29 const rootN = Math.sqrt(x.length);
30
31 // returning the t value
32 return (sampleMean - expectedValue) / (sd / rootN);
33}
34
35export default tTest;