Skip to content

Commit 687b505

Browse files
Add an algorithm to find mean absolute deviation
1 parent d94929e commit 687b505

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

Maths/MeanAbsoluteDeviation.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { mean } from "./AverageMean.js"
2+
/**
3+
*@function meanAbsoluteDeviation
4+
*@description Calculates the mean absolute deviation of list of numbers
5+
* @param {Integer} data
6+
* @returns meanAbsoluteDeviation([2,34,5,0,-2]) = 10.480
7+
* @url https://en.wikipedia.org/wiki/Average_absolute_deviation
8+
*/
9+
function meanAbsoluteDeviation (data) {
10+
if (!Array.isArray(data)) {
11+
throw new TypeError('Invalid Input')
12+
}
13+
let absoluteSum = 0
14+
let meanValue = mean(data)
15+
for (const dataPoint of data) {
16+
absoluteSum += Math.abs(dataPoint - meanValue)
17+
}
18+
return (absoluteSum / data.length).toFixed(3)
19+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import {meanAbsoluteDeviation} from '../MeanAbsoluteDeviation.js'
2+
3+
describe('tests for mean absolute deviation', () => {
4+
it('should be a function', () => {
5+
expect(typeof meanAbsoluteDeviation).toEqual('function')
6+
})
7+
8+
it('should throw an invalid input error', () => {
9+
expect(() => meanAbsoluteDeviation('fgh')).toThrow()
10+
})
11+
12+
it('should return the mean absolute devition of an array of numbers', () => {
13+
const meanAbDev = meanAbsoluteDeviation([2,34,5,0,-2])
14+
expect(meanAbDev).toBe(10.480)
15+
})
16+
})

0 commit comments

Comments
 (0)