Skip to content
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
26 changes: 26 additions & 0 deletions Maths/StandardDeviation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @function standardDeviation
* @description Calculates the standard deviation of an array of numbers.
* Standard deviation measures the amount of variation or dispersion
* in a set of values.
* @param {number[]} arr - An array of numbers
* @returns {number} - The standard deviation
* @see https://en.wikipedia.org/wiki/Standard_deviation
* @example standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) => 2
* @example standardDeviation([1, 2, 3]) => 0.816
*/
const standardDeviation = (arr) => {
if (!Array.isArray(arr) || arr.length === 0) {
throw new TypeError('Input must be a non-empty array')
}
if (!arr.every((n) => typeof n === 'number' && !isNaN(n))) {
throw new TypeError('All elements must be numbers')
}
const mean = arr.reduce((sum, n) => sum + n, 0) / arr.length
const squaredDiffs = arr.map((n) => Math.pow(n - mean, 2))
const avgSquaredDiff =
squaredDiffs.reduce((sum, n) => sum + n, 0) / arr.length
return Math.sqrt(avgSquaredDiff)
}

export { standardDeviation }
39 changes: 39 additions & 0 deletions Maths/test/StandardDeviation.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { standardDeviation } from '../StandardDeviation.js'

describe('standardDeviation', () => {
test('standardDeviation([2,4,4,4,5,5,7,9]) returns 2', () => {
expect(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])).toBe(2)
})

test('standardDeviation([1, 2, 3]) returns ~0.816', () => {
expect(standardDeviation([1, 2, 3])).toBeCloseTo(0.816)
})

test('standardDeviation of identical elements returns 0', () => {
expect(standardDeviation([5, 5, 5, 5])).toBe(0)
})

test('standardDeviation single element returns 0', () => {
expect(standardDeviation([42])).toBe(0)
})

test('standardDeviation works with negative numbers', () => {
expect(standardDeviation([-2, -1, 0, 1, 2])).toBeCloseTo(1.414)
})

test('standardDeviation works with decimals', () => {
expect(standardDeviation([1.5, 2.5, 3.5])).toBeCloseTo(0.816)
})

test('throws TypeError for empty array', () => {
expect(() => standardDeviation([])).toThrow(TypeError)
})

test('throws TypeError for non-array input', () => {
expect(() => standardDeviation('123')).toThrow(TypeError)
})

test('throws TypeError for array with non-numbers', () => {
expect(() => standardDeviation([1, 'two', 3])).toThrow(TypeError)
})
})
Loading