Skip to content

Commit 264c7ae

Browse files
feat: add standard deviation algorithm
1 parent 5c39e87 commit 264c7ae

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

‎Maths/StandardDeviation.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function standardDeviation
3+
* @description Calculates the standard deviation of an array of numbers.
4+
* Standard deviation measures the amount of variation or dispersion
5+
* in a set of values.
6+
* @param {number[]} arr - An array of numbers
7+
* @returns {number} - The standard deviation
8+
* @see https://en.wikipedia.org/wiki/Standard_deviation
9+
* @example standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) => 2
10+
* @example standardDeviation([1, 2, 3]) => 0.816
11+
*/
12+
const standardDeviation = (arr) => {
13+
if (!Array.isArray(arr) || arr.length === 0) {
14+
throw new TypeError('Input must be a non-empty array')
15+
}
16+
if (!arr.every((n) => typeof n === 'number' && !isNaN(n))) {
17+
throw new TypeError('All elements must be numbers')
18+
}
19+
const mean = arr.reduce((sum, n) => sum + n, 0) / arr.length
20+
const squaredDiffs = arr.map((n) => Math.pow(n - mean, 2))
21+
const avgSquaredDiff =
22+
squaredDiffs.reduce((sum, n) => sum + n, 0) / arr.length
23+
return Math.sqrt(avgSquaredDiff)
24+
}
25+
26+
export { standardDeviation }
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { standardDeviation } from '../StandardDeviation.js'
2+
3+
describe('standardDeviation', () => {
4+
test('standardDeviation([2,4,4,4,5,5,7,9]) returns 2', () => {
5+
expect(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])).toBe(2)
6+
})
7+
8+
test('standardDeviation([1, 2, 3]) returns ~0.816', () => {
9+
expect(standardDeviation([1, 2, 3])).toBeCloseTo(0.816)
10+
})
11+
12+
test('standardDeviation of identical elements returns 0', () => {
13+
expect(standardDeviation([5, 5, 5, 5])).toBe(0)
14+
})
15+
16+
test('standardDeviation single element returns 0', () => {
17+
expect(standardDeviation([42])).toBe(0)
18+
})
19+
20+
test('standardDeviation works with negative numbers', () => {
21+
expect(standardDeviation([-2, -1, 0, 1, 2])).toBeCloseTo(1.414)
22+
})
23+
24+
test('standardDeviation works with decimals', () => {
25+
expect(standardDeviation([1.5, 2.5, 3.5])).toBeCloseTo(0.816)
26+
})
27+
28+
test('throws TypeError for empty array', () => {
29+
expect(() => standardDeviation([])).toThrow(TypeError)
30+
})
31+
32+
test('throws TypeError for non-array input', () => {
33+
expect(() => standardDeviation('123')).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for array with non-numbers', () => {
37+
expect(() => standardDeviation([1, 'two', 3])).toThrow(TypeError)
38+
})
39+
})

0 commit comments

Comments
 (0)