Skip to content

Instantly share code, notes, and snippets.

@alexreardon
Created May 17, 2023 01:36
Show Gist options
  • Save alexreardon/17401f0f102c7f8f2080e25dca18bf74 to your computer and use it in GitHub Desktop.
Save alexreardon/17401f0f102c7f8f2080e25dca18bf74 to your computer and use it in GitHub Desktop.
function average(values: number[]): number {
const sum = values.reduce((acc, current) => acc + current, 0);
return sum / values.length;
}
export function standardDeviation(values: number[]): number {
/** https://www.mathsisfun.com/data/standard-deviation-formulas.html
* 1. Work out the Mean (the simple average of the numbers)
* 2. Then for each number: subtract the Mean and square the result
* 3. Then work out the mean of those squared differences.
* 4. Take the square root of that and we are done! */
const mean = average(values);
const squaredDifferences = values.map((value) => Math.pow(value - mean, 2));
const differenceMean = average(squaredDifferences);
const result = Math.sqrt(differenceMean);
return result;
}
export function zScores(values: number[]): number[] {
// https://statisticsbyjim.com/basics/outliers/
const mean = average(values);
const deviation = standardDeviation(values);
const zScores = values.map((value) => {
if (deviation === 0) {
return 0;
}
return (value - mean) / deviation;
});
return zScores;
}
export function p50(values: number[]): number {
const p50Index = Math.floor(values.length / 2);
const smallestToBiggest = [...values].sort((a, b) => a - b);
return smallestToBiggest[p50Index];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment