how to generate bins for histogram using apache math 3.0 in java?
As far as I know there is no good histogram class in Apache Commons. I ended up writing my own. If all you want are linearly distributed bins from min to max, then it is quite easy to write.
Maybe something like this:
public static int[] calcHistogram(double[] data, double min, double max, int numBins) {
final int[] result = new int[numBins];
final double binSize = (max - min)/numBins;
for (double d : data) {
int bin = (int) ((d - min) / binSize);
if (bin < 0) { /* this data is smaller than min */ }
else if (bin >= numBins) { /* this data point is bigger than max */ }
else {
result[bin] += 1;
}
}
return result;
}
Edit: Here's an example.
double[] data = { 2, 4, 6, 7, 8, 9 };
int[] histogram = calcHistogram(data, 0, 10, 4);
// This is a histogram with 4 bins, 0-2.5, 2.5-5, 5-7.5, 7.5-10.
assert histogram[0] == 1; // one point (2) in range 0-2.5
assert histogram[1] == 1; // one point (4) in range 2.5-5.
// etc..
I think your code has a bug in it -- please see the corrected code below:
public static int[] calcHistogram(double[] data, double min, double max, int numBins) {
final int[] result = new int[numBins];
final double binSize = (max - min)/numBins;
for (double d : data) {
int bin = (int) ((d - min) / binSize); // changed this from numBins
if (bin < 0) { /* this data is smaller than min */ }
else if (bin >= numBins) { /* this data point is bigger than max */ }
else {
result[bin] += 1;
}
}
return result;
}
Here is a simple way to implement histogram using Apache Commons Math 3:
final int BIN_COUNT = 20;
double[] data = {1.2, 0.2, 0.333, 1.4, 1.5, 1.2, 1.3, 10.4, 1, 2.0};
long[] histogram = new long[BIN_COUNT];
org.apache.commons.math3.random.EmpiricalDistribution distribution = new org.apache.commons.math3.random.EmpiricalDistribution(BIN_COUNT);
distribution.load(data);
int k = 0;
for(org.apache.commons.math3.stat.descriptive.SummaryStatistics stats: distribution.getBinStats())
{
histogram[k++] = stats.getN();
}