Skip to content

feat: Added Standard Deviation algorithm for Math #1680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Maths/StandardDeviation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Returns the standard deviation given an array of integers
* @param number[] nums array of integers
* @return number 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 (typeof nums[i] != 'number') {
throw new TypeError('Number 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 }
36 changes: 36 additions & 0 deletions Maths/test/StandardDeviation.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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()
})