如何在 JavaScript(或 PHP)中获取数组的中位数和四分位数/百分位数? [英] How to get median and quartiles/percentiles of an array in JavaScript (or PHP)?

查看:133
本文介绍了如何在 JavaScript(或 PHP)中获取数组的中位数和四分位数/百分位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题变成了问答,因为我很难找到答案,并认为它对其他人有用

This question is turned into a Q&A, because I had struggle finding the answer, and think it can be useful for others

我有一个 JavaScript 值数组,需要在 JavaScript 中计算它的 Q2(第 50 个百分点,又名中位数),Q1(第 25 个百分点) 和 Q3(第 75 个百分位)值.

I have a JavaScript array of values and need to calculate in JavaScript its Q2 (50th percentile aka MEDIAN), Q1 (25th percentile) and Q3 (75th percentile) values.

推荐答案

我更新了第一个答案中的 JavaScript 翻译,以使用箭头函数和更简洁的符号.除了 std 之外,功能基本保持不变,它现在计算样本标准偏差(除以 arr.length - 1 而不是仅仅 arr.length)

I updated the JavaScript translation from the first answer to use arrow functions and a bit more concise notation. The functionality remains mostly the same, except for std, which now computes the sample standard deviation (dividing by arr.length - 1 instead of just arr.length)

// sort array ascending
const asc = arr => arr.sort((a, b) => a - b);

const sum = arr => arr.reduce((a, b) => a + b, 0);

const mean = arr => sum(arr) / arr.length;

// sample standard deviation
const std = (arr) => {
    const mu = mean(arr);
    const diffArr = arr.map(a => (a - mu) ** 2);
    return Math.sqrt(sum(diffArr) / (arr.length - 1));
};

const quantile = (arr, q) => {
    const sorted = asc(arr);
    const pos = (sorted.length - 1) * q;
    const base = Math.floor(pos);
    const rest = pos - base;
    if (sorted[base + 1] !== undefined) {
        return sorted[base] + rest * (sorted[base + 1] - sorted[base]);
    } else {
        return sorted[base];
    }
};

const q25 = arr => quantile(arr, .25);

const q50 = arr => quantile(arr, .50);

const q75 = arr => quantile(arr, .75);

const median = arr => q50(arr);

这篇关于如何在 JavaScript(或 PHP)中获取数组的中位数和四分位数/百分位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆