Skip to content

Commit

Permalink
fix: median absolute deviation calculation (#236)
Browse files Browse the repository at this point in the history
Signed-off-by: Péter Pallos <[email protected]>
Signed-off-by: Jérôme Benoit <[email protected]>
  • Loading branch information
jerome-benoit authored Jan 29, 2025
1 parent c9816af commit e9c4a6a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,15 @@ const quantileSorted = (samples: number[], q: number) => {
return samples[baseIndex]
}

/**
* Computes the median of a sample.
* @param samples - the sample
* @returns the median of the sample
*/
const median = (samples: number[]) => {
return medianSorted(samples.sort((a, b) => a - b))
}

/**
* Computes the median of a sorted sample.
* @param samples - the sorted sample
Expand Down Expand Up @@ -316,7 +325,7 @@ export const getStatisticsSorted = (samples: number[]): Statistics => {
aad: absoluteDeviation(samples, average, mean),
critical,
df,
mad: absoluteDeviation(samples, medianSorted, p50),
mad: absoluteDeviation(samples, median, p50),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
max: samples[df]!,
mean,
Expand Down
8 changes: 8 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { expect, test } from 'vitest'

import { getStatisticsSorted } from '../src/utils'

test('median absolute deviation', () => {
const stats = getStatisticsSorted([1, 2, 3])
expect(stats.mad).toBe(1)
})

0 comments on commit e9c4a6a

Please sign in to comment.