I'm trying to come up with the best way of doing some kind of switch style selection on a double to find out what range it is in. Something like this:
double a = 1.1;
switch(a)
{
case: (0.0, 1.6)
return 1;
case: (1.6, 2.337)
return 2;
case: (2.337, 3.2974)
return 3;
default:
return -1;
}
Obviously in this example, one value in the range would have to be non-inclusive, but you get my drift. Any Ideas?
Edit, the ranges are not necessarily integral.
EDIT 2: I'm actually dealing with radians and finding out which of 12 ranges a point is in. I ended up doing this:
double pi = Math.PI;
double[] zones = new double[] {
0, pi/6, pi/3, pi/2,
2*pi/3, 5*pi/6, pi, 7*pi/6,
4*pi/3, 3*pi/2, 5*pi/3, 11*pi/6
};
for (int i = 0; i < 11; i++)
{
if (radians > zones[i] && radians <= zones[i + 1])
{
return i + 1;
}
}
I started to do an binary search type if-else, but it was going to get too messy.
The following is ideally suited to adjacent ranges, since you only need to write the range limits once:
double a = 1.1;
if (a < 0.0) {
// Too low
return -1;
} else if (a < 1.6) {
// Range [0.0, 1.6)
return 1;
} else if (a < 2.337) {
// Range [1.6, 2.337)
return 2;
} else if (a < 3.2974) {
// Range [2.337, 3.2974)
return 3;
} else {
// Too high
return -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With