Skip to content

Commit

Add mean, median, and standard_deviation to math.js

g1tbot and Claudeagentcommitted Parentf111277Browse files
2 files+33−10/2 viewed
+26−1
2121 return result;
2222 }
2323
24−module.exports = { add, multiply, power };
24+/** Returns the average of numbers; throws a TypeError if the array is empty. */
25+function mean(numbers) {
26+ if (numbers.length === 0) {
27+ throw new TypeError("numbers must not be empty");
28+ }
29+ return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
30+}
31+
32+/** Returns the middle value of numbers (the average of the two middle values when the length is even); throws a TypeError if the array is empty. */
33+function median(numbers) {
34+ if (numbers.length === 0) {
35+ throw new TypeError("numbers must not be empty");
36+ }
37+ const sorted = [...numbers].sort((a, b) => a - b);
38+ const mid = Math.floor(sorted.length / 2);
39+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
40+}
41+
42+/** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */
43+function standard_deviation(numbers) {
44+ const avg = mean(numbers);
45+ const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length;
46+ return Math.sqrt(variance);
47+}
48+
49+module.exports = { add, multiply, power, mean, median, standard_deviation };
+7−0
66 assert.strictEqual(math.power(2, 10), 1024);
77 assert.strictEqual(math.power(5, 0), 1);
88 assert.throws(() => math.power(2, -1), RangeError);
9+assert.strictEqual(math.mean([1, 2, 3, 4]), 2.5);
10+assert.strictEqual(math.median([3, 1, 2]), 2);
11+assert.strictEqual(math.median([4, 1, 3, 2]), 2.5);
12+assert.strictEqual(math.standard_deviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
13+for (const fn of [math.mean, math.median, math.standard_deviation]) {
14+ assert.throws(() => fn([]), TypeError);
15+}
916 console.log("all tests passed");