locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
37 lines (36 loc) • 1.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.median_grouped = median_grouped;
const _statistics_ts_1 = require("../_helpers/_statistics.js");
function median_grouped(data, interval = 1) {
// discuss at: https://locutus.io/python/statistics/median_grouped/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Estimates the median for data binned around interval midpoints using grouped interpolation.
// example 1: median_grouped([52, 52, 53, 54])
// returns 1: 52.5
// example 2: median_grouped([52, 52, 53, 54], 2)
// returns 2: 52
// example 3: median_grouped([true, false, true])
// returns 3: 0.75
const values = (0, _statistics_ts_1.sortStatisticsValues)((0, _statistics_ts_1.assertStatisticsArray)(data, 'median_grouped'), 'median_grouped');
const n = values.length;
if (n === 0) {
throw new Error('no median for empty data');
}
const x = values[Math.floor(n / 2)];
let i = 0;
while (i < values.length && values[i] !== x) {
i += 1;
}
let j = i;
while (j < values.length && values[j] === x) {
j += 1;
}
const numericInterval = (0, _statistics_ts_1.toFloatStatisticNumber)(interval, 'median_grouped');
const numericX = (0, _statistics_ts_1.toFloatStatisticNumber)(x, 'median_grouped');
const lowerLimit = numericX - numericInterval / 2;
const cumulativeFrequency = i;
const frequency = j - i;
return lowerLimit + (numericInterval * (n / 2 - cumulativeFrequency)) / frequency;
}