From 31ccdbf38f27546253ec4c1f4815d28319829124 Mon Sep 17 00:00:00 2001 From: Justin Zou Date: Sat, 13 Jul 2024 18:00:13 -0400 Subject: [PATCH] feat: StandardDeviation algorithm for Math --- Maths/StandardDeviation.js | 34 ++++++++++++++++++++++++++++ Maths/test/StandardDeviation.test.js | 32 ++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Maths/StandardDeviation.js create mode 100644 Maths/test/StandardDeviation.test.js diff --git a/Maths/StandardDeviation.js b/Maths/StandardDeviation.js new file mode 100644 index 0000000000..34dc1fa14b --- /dev/null +++ b/Maths/StandardDeviation.js @@ -0,0 +1,34 @@ + +/* + * Returns the standard deviation given an array of integers + * @param int[] nums array of integers + * @return int standard deviation + * @see https://en.wikipedia.org/wiki/Standard_deviation + */ +function standardDeviation(nums) { + + if (nums.length < 2) { + throw new Error("At least two numbers in input array are required!"); + } + if (!Array.isArray(nums)) { + throw new TypeError("Array required!"); + } + + let sum = 0; + for (let i = 0; i < nums.length; i++) { + if (!Number.isInteger(nums[i])) { + throw new TypeError("Integer type required in array input!"); + } + sum += nums[i]; + } + let avg = sum/nums.length; + let deviationSquareSum = 0; + for (let i = 0; i < nums.length; i++) { + let square = Math.pow((nums[i]-avg),2); + deviationSquareSum += square; + } + + return(Math.sqrt(deviationSquareSum/nums.length)); +} + +export {standardDeviation} \ No newline at end of file diff --git a/Maths/test/StandardDeviation.test.js b/Maths/test/StandardDeviation.test.js new file mode 100644 index 0000000000..e62f4492e2 --- /dev/null +++ b/Maths/test/StandardDeviation.test.js @@ -0,0 +1,32 @@ +import { standardDeviation } from "../StandardDeviation.js"; + +test("Calculate STD of 3,5,6,10,23,12,19", ()=>{ + expect(standardDeviation([3,5,6,10,23,12,19])).toBeCloseTo(6.9164105353773); +}) + +test("Calculate STD of -2,-5,1,12,23,-81,-23", () => { + expect(standardDeviation([-2,-5,1,12,23,-81,-23])).toBeCloseTo(31.598889156399); +}) + +test("Calculate STD of 0,0,0", () => { + expect(standardDeviation([0,0,0])).toBeCloseTo(0); +}) + +test("Calculate STD of -7,7", () => { + expect(standardDeviation([-7,7])).toBeCloseTo(7); +}) + +test("Throw error - array has less than two items", () => { + expect(() => standardDeviation([])).toThrow(); + expect(() => standardDeviation([7])).toThrow(); +}) + +test("Throw type error - not an array", () => { + expect(() => standardDeviation(2)).toThrow(); + expect(() => standardDeviation("not an array")).toThrow(); +}) + +test("Throw type error - not a number inside array", () => { + expect(() => standardDeviation([5,"not a number",2])).toThrow(); + expect(() => standardDeviation([1,[2],3])).toThrow(); +}) \ No newline at end of file