When multiplying a floating point number that is very close to 1 with an int > 0, can it ever be interpreted as 1.
That is, if Math.random() returns its highest possible result (which is 1 step below 1.0), will
(int)(Math.random() * 8)
be 8 or 7?
For a practical example, can this often-used construct give an index out of bounds error:
someArray[(int)(Math.random() * someArray.length)];
I’m specifically interested in answers for Java and ActionScript 3, but I suppose they all use the same rules for floating point arithmetic, and answers for any platform would be useful.
Update: Though I already accepted an answer, I’d still appreciate confirmation that this can’t go wrong in ActionScript 3 either, since a colleague reporting that he saw it go wrong once is what partly prompted me to ask this question.
If you multiply the greatest value below 1.0 with
someInt(> 0), the result will never besomeInt.This can be exhaustively tested for integers like this:
The snippet produces no output.
(
Math.ulpreturns the distance between the given double and the double value next larger in magnitude. The assertion thus ensures thatgreatestLessThanOneis indeed the greatest value less than 1.0.)In other words, your line
will never give rise to an ArrayIndexOutOfBoundsException.
Furthermore, according to Mark Dickinsons comment over here, this holds also when multiplying with a double.