首页 > 解决方案 > 从对象列表中查找 tercile

问题描述

我需要帮助如何计算三分位数。我的数据集示例:

ImmutableList<Double> DataSet = ImmutableList.of(25.0, 100.0, 0.0, 144.0, 9.0, 121.0, 4.0, 225.0, 169.0, 64.0, 49.0, 16.0, 36.0, 1.0, 81.0, 196.0);
double[] dataset = Doubles.toArray(DataSet);

我尝试使用Google Guava来计算中位数,但我不知道如何使用它来计算三分位数:

import java.util.Map;

import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Doubles;
import com.google.common.math.Quantiles;
import com.google.common.math.Quantiles.ScaleAndIndexes;

public class Main {
    public static void main(String[] args) {
        ImmutableList<Double> DataSet = ImmutableList.of(25.0, 100.0,
                  0.0, 144.0, 9.0, 121.0, 4.0, 225.0, 169.0, 64.0, 49.0, 16.0, 36.0, 1.0, 81.0, 196.0);
        double[] dataset = Doubles.toArray(DataSet);

        double median = Quantiles.median().compute(dataset);
        System.out.println(median);

    }
}

标签: javaquantile

解决方案


Tercile 是三分位数。番石榴有这个方法:

public static Quantiles.Scale scale(int scale)
Specifies the computation of q-quantiles.
Parameters:
scale - the scale for the quantiles to be calculated, i.e. the q of the q-quantiles, which must be positive

所以你可以做

Quantiles.scale(3).compute(...)

UPD

似乎番石榴(和谷歌)有它自己的 terciles 概念。它考虑了实际值,并根据值而不是索引来查找 tercile。

如果这不是您所追求的,而您需要的只是简单的基于索引的 tercile,那么您实际上并不需要一个库,只需自己编写即可(显然您需要先对数据进行排序,并考虑角案例):

static double[] terciles(double[] data) {
    data = data.clone();
    Arrays.sort(data);
    int len = data.length;
    if (len < 2)
        throw new IllegalArgumentException();
    double result[] = new double[2];
    result[0] = data[len/3];
    result[1] = data[2*len/3];
    return result;
}

推荐阅读