but if 160.999999998 is truncated to 160, 159.99999998 must be
truncated to 159.....
True, but where did you get 159.99999998?
The problem is that, sometimes, the result of (yhi-ylo)/stepY will not be an
exact integer, because stepY may not be exactly representable in binary (as
a double or float). So sometimes your array size will be too small.
The solution for handling this depends on your goal. How are you later
using the array elements?
In your example, stepY is 0.1, or 1/10, which means you're expecting to get
(yhi-ylo)*10 = 160, right? Well, where does stepY come from? Can you
compute it from something like 1/numElementsPerUnit, where
numElementsPerUnit is an integer? If so, your code could change to:
nbNiveau = (yhi-ylo)*numElementsPerUnit + 1;
stepY = 1 / numElementsPerUnit;
That would avoid the issue entirely.
If stepY is not representable that way, and if yhi-ylo isn't too big, you
could just add 1.1 instead of 1 before truncating to an integer, but that's
not the prefered solution.
Victor's idea of "bumping up" the value might work for you, as well, if all
you care about is having "enough" elements in the array.
One thing to note: If you ever make calculations like (i-ylo)/stepY, or
simply i*stepY, then for large values of i the result will get further and
further from what you expect. But that's probably not be a problem for you,
since your values are small.
By the way, one thing I like to do when investigating problems involving
calculations like this is to store intermediate results to another variable,
like this:
double temp = (yhi-ylo)/stepY +1;
long nbNiveau = temp;
This lets you examine the values yourself when debugging, instead of trying
to guess what's going on inside the program.
Hope this helps...
-Howard