public static AssociativeArray percentiles ( FlatDataCollection flatDataCollection , int cutPoints ) { double [ ] doubleArray = flatDataCollection . stream ( ) . filter ( x -> x != null ) . mapToDouble ( TypeInference :: toDouble ) . toArray ( ) ; int n = doubleArray . length ; if ( n <= 0 || cutPoints <= 0 || n < cutPoints ) { throw new IllegalArgumentException ( "All the parameters must be positive and n larger than cutPoints." ) ; } Arrays . sort ( doubleArray ) ; /* Uses the Haverage algorithm which is used by SPSS as described at: http://publib.boulder.ibm.com/infocenter/spssstat/v20r0m0/index.jsp?topic=%2Fcom.ibm.spss.statistics.help%2Falg_examine_haverage.htm */ AssociativeArray percintiles = new AssociativeArray ( ) ; double counter = 1.0 ; while ( true ) { double perc = counter / cutPoints ; Double tc2 = ( n + 1.0 ) * perc ; int CCk2 = tc2 . intValue ( ) ; int CCk2_plus1 = CCk2 + 1 ; int Ck2 = CCk2 - 1 ; //actual pointers on the table. These are used because the arrays start from 0 the counting int Ck2_plus1 = CCk2_plus1 - 1 ; double g2Star = tc2 - CCk2 ; if ( Ck2 < doubleArray . length ) { Double key = 100 * perc ; Double Ck2Value = doubleArray [ Ck2 ] ; if ( Ck2_plus1 < doubleArray . length ) { Double Ck2_plus1Value = doubleArray [ Ck2_plus1 ] ; percintiles . put ( key , ( 1 - g2Star ) * Ck2Value + g2Star * Ck2_plus1Value ) ; } else { percintiles . put ( key , Ck2Value ) ; break ; } } else { break ; } ++ counter ; } return percintiles ; }
Calculates the percentiles given a number of cutPoints