采用五分位算法,统计一下数据的分布情况
首先,我们设置一下五分位算法点位K值,分别采用 16%,37%,63%,84%概率
根据excel自带的函数PERCENTILE,以及 K值,分别计算出四个点位值,结果如下图所示
虽然excel有自带的函数,但是java没有,必须通过自己编写程序来实现
创建 Method.java类
package com.test; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Method { /** * 五分位算法 * @author Administrator * */ public static double caculateQuinte(double[] data,int k) { double point = 0.00; try { List<Double> list = Method.createList(data); point = Method.getValue(list, k); } catch (Exception e) { e.printStackTrace(); } return point; } /** * 计算点位值 * @param list * @param p * @return */ public static double getValue(List<Double> list,int p){ //list大小 int n = list.size(); double doubleData = ((double)(n-1)*p)/100; //整数部分 int i = (n-1)*p/100; DecimalFormat decimalFormat = new DecimalFormat("########0.000000000"); //小数部分 double j = Double.parseDouble(decimalFormat.format(doubleData - i)); //第i个元素值 double a = list.get(i); //第i+1个元素值 double b = list.get(i+1); return Double.parseDouble(decimalFormat.format(((1-j)*a)+(j*b))); } /** * 倒排序 * @param dd * @return */ @SuppressWarnings("unchecked") public static List<Double> createList(double...dd){ List<Double> list = new ArrayList<Double>(); for(Double db : dd ){ list.add(db); } @SuppressWarnings("rawtypes") Comparator comparator = new Comparator() { @Override public int compare(Object o1, Object o2) { double d1 = (double)o1; double d2 = (double)o2; if(d1 > d2){ return 1; }else if(d1 == d2){ return 0; }else{ return -1; } } }; Collections.sort(list,comparator); return list; } }
标红的地方说明一下:我查看过其他网友对PERCENTILE原理的描述,他们说 a 和 b,分别取 i+1 和 i+2的值,但是我按照他们说的,计算出来的结果不对(http://www.360doc.com/content/15/0718/17/26365336_485725251.shtml)
写一个测试类Test.java
package com.test; public class Test { public static void main(String[] args) { double[] dd = { 4.5077089, 2.8531679, 2.5365171, 2.5248491, 2.2526313, 1.2222833, 0.8638264, 0.7489835, 0.7429955, 0.6211575, 0.5247851, 0.4948757, 0.4946506, 0.4172792, 0.3435438, 0.1663883, -0.014807, -0.06503, -0.334462, -0.430975, -0.478554, -2.720794, -3.328721, -5.205578 }; int[] k = {16,37,63,84}; System.out.println(Method.caculateQuinte(dd, k[0])); System.out.println(Method.caculateQuinte(dd, k[1])); System.out.println(Method.caculateQuinte(dd, k[2])); System.out.println(Method.caculateQuinte(dd, k[3])); } }
看下结果,如下图所示
与excel自带函数计算出的结果完全一致