Skip to content

Commit 31ccdbf

Browse files
committed
feat: StandardDeviation algorithm for Math
1 parent 9010481 commit 31ccdbf

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Maths/StandardDeviation.js

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

Maths/test/StandardDeviation.test.js

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

0 commit comments

Comments
 (0)