Skip to content

Commit

Permalink
Merge pull request #184 from frauzufall/percentile
Browse files Browse the repository at this point in the history
Percentile enhancement
  • Loading branch information
tpietzsch authored Oct 9, 2017
2 parents bba835d + 6542d8f commit 838e7c8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/main/java/net/imglib2/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,11 @@ public static double percentile( final double[] values, final double percentile
{
final double temp[] = values.clone();
final int length = temp.length;
final int pos = Math.min( length - 1, Math.max( 0, ( int ) Math.round( ( length - 1 ) * percentile ) ) );

quicksort( temp );
KthElement.kthElement( pos, temp );

return temp[ Math.min( length - 1, Math.max( 0, ( int ) Math.round( ( length - 1 ) * percentile ) ) ) ];
return temp[ pos ];
}

public static double averageDouble( final List< Double > values )
Expand Down Expand Up @@ -306,6 +307,11 @@ public static float median( final float[] values )

return median;
}

public static void quicksort( final long[] data )
{
quicksort( data, 0, data.length - 1 );
}

public static void quicksort( final long[] data, final int left, final int right )
{
Expand Down
34 changes: 34 additions & 0 deletions src/test/java/net/imglib2/util/ImgUtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,13 @@

package net.imglib2.util;

import static net.imglib2.util.Util.percentile;
import static net.imglib2.util.Util.quicksort;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import net.imglib2.RandomAccess;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgFactory;
Expand All @@ -52,6 +57,35 @@
*/
public class ImgUtilTest
{

@Test
public void testPercentile()
{
final double[] data = new double[42];
for(int i = 0; i < data.length; i++) {
data[i] = Math.random()*42;
}
final double[] sortedData = data.clone();
final double[] quicksortedData = data.clone();
Arrays.sort( sortedData );
quicksort( quicksortedData );

for(int i = 0; i < 3; i++){

double percentile = Math.random();

int pos = Math.min( data.length - 1,
Math.max( 0, ( int ) Math.round( ( data.length - 1 ) * percentile ) ) );

final double percentileRes = percentile( data, percentile );

assertEquals(quicksortedData[pos], sortedData[pos], 0.001);
assertEquals(quicksortedData[pos], percentileRes, 0.001);

}


}

@Test
public void testCopyDoubleArrayIntIntArrayImgOfT()
Expand Down

0 comments on commit 838e7c8

Please sign in to comment.