Skip to content

Commit 1f13f09

Browse files
committed
feat: Added Standard Deviation algorithm for Math
1 parent 9010481 commit 1f13f09

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

Maths/StandardDeviation.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Returns the standard deviation given an array of integers
3+
* @param int[] nums array of integers
4+
* @return int standard deviation
5+
* @see https://en.wikipedia.org/wiki/Standard_deviation
6+
*/
7+
function standardDeviation(nums) {
8+
if (nums.length < 2) {
9+
throw new Error('At least two numbers in input array are required!')
10+
}
11+
if (!Array.isArray(nums)) {
12+
throw new TypeError('Array required!')
13+
}
14+
15+
let sum = 0
16+
for (let i = 0; i < nums.length; i++) {
17+
if (!Number.isInteger(nums[i])) {
18+
throw new TypeError('Integer type required in array input!')
19+
}
20+
sum += nums[i]
21+
}
22+
let avg = sum / nums.length
23+
let deviationSquareSum = 0
24+
for (let i = 0; i < nums.length; i++) {
25+
let square = Math.pow(nums[i] - avg, 2)
26+
deviationSquareSum += square
27+
}
28+
29+
return Math.sqrt(deviationSquareSum / nums.length)
30+
}
31+
32+
export { standardDeviation }

Maths/test/StandardDeviation.test.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { standardDeviation } from '../StandardDeviation.js'
2+
3+
test('Calculate STD of 3,5,6,10,23,12,19', () => {
4+
expect(standardDeviation([3, 5, 6, 10, 23, 12, 19])).toBeCloseTo(
5+
6.9164105353773
6+
)
7+
})
8+
9+
test('Calculate STD of -2,-5,1,12,23,-81,-23', () => {
10+
expect(standardDeviation([-2, -5, 1, 12, 23, -81, -23])).toBeCloseTo(
11+
31.598889156399
12+
)
13+
})
14+
15+
test('Calculate STD of 0,0,0', () => {
16+
expect(standardDeviation([0, 0, 0])).toBeCloseTo(0)
17+
})
18+
19+
test('Calculate STD of -7,7', () => {
20+
expect(standardDeviation([-7, 7])).toBeCloseTo(7)
21+
})
22+
23+
test('Throw error - array has less than two items', () => {
24+
expect(() => standardDeviation([])).toThrow()
25+
expect(() => standardDeviation([7])).toThrow()
26+
})
27+
28+
test('Throw type error - not an array', () => {
29+
expect(() => standardDeviation(2)).toThrow()
30+
expect(() => standardDeviation('not an array')).toThrow()
31+
})
32+
33+
test('Throw type error - not a number inside array', () => {
34+
expect(() => standardDeviation([5, 'not a number', 2])).toThrow()
35+
expect(() => standardDeviation([1, [2], 3])).toThrow()
36+
})

0 commit comments

Comments
 (0)