【问题标题】:How do I easily implement the Matlab percentile in Java?如何在 Java 中轻松实现 Matlab 百分位数?
【发布时间】:2021-11-14 12:36:42
【问题描述】:

我需要为一个简单的案例复制 Matlab 百分位数 (https://www.mathworks.com/help/stats/prctile.html) percentile(double[] arr, int percentile) 在 java 中。我找不到任何可以给我相同结果的实现,因为它似乎有一个百分位数和线性插值。

感谢任何帮助或指导!

【问题讨论】:

  • 好的,你想要的值与prctile 返回的值完全相同,我已经更新了答案

标签: java matlab math interpolation percentile


【解决方案1】:

通过直接应用定义(您可以在您链接的页面中找到)

// `xs` must be sorted
double percentile(double [] xs, int p) {
    // The sorted elements in X are taken as the 100(0.5/n)th, 100(1.5/n)th, ..., 100([n – 0.5]/n)th percentiles.
    int i = (int) (p * xs.length / 100.0 - 0.5);

    // Linear interpolation uses linear polynomials to find yi = f(xi), the values of the underlying function
    // Y = f(X) at the points in the vector or array x. Given the data points (x1, y1) and (x2, y2), where
    // y1 = f(x1) and y2 = f(x2), linear interpolation finds y = f(x) for a given x between x1 and x2 as follows:
    return xs[i] + (xs[i + 1] - xs[i]) * (p / 100.0 - (i + 0.5) / xs.length) / ((i + 1.5) / xs.length - (i + 0.5) / xs.length);
}

使用该页面上的示例

double [] xs1 = new double[] {6.0753, 8.6678, 0.4823, 6.7243, 5.6375, 2.3846, 4.1328, 5.6852, 12.1568, 10.5389};
Arrays.sort(xs1);
double r = percentile(xs1, 42);
System.out.println("Result: " + r);
System.out.println("Error: " + Math.abs(r - 5.6709));

你得到

Result: 5.67089
Error: 9.999999999621423E-6

【讨论】:

    【解决方案2】:

    @josejuan 的回答很好:但是i 等于xs.length - 1 的情况是不是没必要处理?我将修改percentile函数的return公式如下:

    return i != (xs.length - 1) ? xs[i] + (xs[i + 1] - xs[i]) * (p / 100.0 - (i + 0.5) / xs.length) / ((i + 1.5) / xs.length - (i + 0.5) / xs.length) : xs[i];
    
    

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多