Inquisitive
Inquisitive

Reputation: 7836

How can I divide a range into n equal bins?

I have a range [min-max]. min and max are of type double. I want to divide this interval into n equal intervals.(n is an integer). How can I achieve this in Java?

For example : say I have a range [10-50]. and n=4 . output should be a list of ranges like [10-20] [20-30][30-40] [40-50]

Upvotes: 3

Views: 14209

Answers (3)

masotann
masotann

Reputation: 911

What you can do is use what @Achintya used, double dist = (double)(max-min)/n; Then starting from the min, add dist to it and that is the max of your first interval.

So it'd be something like: [min, min + dist], [min + dist, min + 2*dist]... until min + n*dist >= max.

int counter = 0;
while(true) {
    CreateInterval(min + counter*dist, min + (counter+1)*dist);
    if (min+(counter+1)*dist >= max) {
         //if we have reached the max, we are done
         break;
    }
}

Upvotes: 1

user1983983
user1983983

Reputation: 4841

If have the Range given in the form of an array with two elements (min and max)

double[] range = new double[] {min, max};
int n = 4;

you could try it this way. What you get from divideRange is a two-dimensional array with subranges of the given range, with each of them having the wanted length.

public double[][] divideRange(double[] range, n) {
    double[][] ranges = new double[n][2];
    double length = (range[1] - range[0])/n;
    ranges[0][0] = range[0];
    ranges[0][1] = range[0]+length;
    for(int i = 1; i < n; i++) {
        ranges[i][0] = ranges[i-1][1];
        ranges[i][1] = ranges[i-1][1]+length;
    }

    return ranges;
}

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

So what you need here is a formula for the limits of the smaller ranges. First lets start off by computing the length of each small range:

// let range be [start, end]
// let the number of smaller ranges be n
double total_length = end - start;
double subrange_length = total_length/n;

After that do a simple cycle for the smaller ranges moving the left end of the current range with the value computed above on each step:

double current_start = start;
for (int i = 0; i < n; ++i) {
  System.out.printl("Smaller range: [" + current_start + ", " + (current_start + subrange_length) + "]");
  current_start += subrange_length;
}

Upvotes: 3

Related Questions