Velocity Reviews > Java > Bad documentation on java.util.Random#nextInt(int)

tyrandor3@gmail.com
Guest
Posts: n/a

 01-03-2008
reference
http://java.sun.com/javase/6/docs/ap...ml#nextInt(int)

do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);

big problem

bits>=0
n>0
n<=bits
therefore
0<=bits%n<bits
therefore bits-bits%n > 0
therefore bits-bits%n+n-1 > 0
therefore bits-bits+n-1<0 is always false?

So how can this loop ever iterate more than once as the documentation
says it can.

Patricia Shanahan
Guest
Posts: n/a

 01-03-2008
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> reference
> http://java.sun.com/javase/6/docs/ap...ml#nextInt(int)
>
> do {
> bits = next(31);
> val = bits % n;
> } while (bits - val + (n-1) < 0);
>
>
> big problem
>
> bits>=0
> n>0
> n<=bits
> therefore
> 0<=bits%n<bits
> therefore bits-bits%n > 0
> therefore bits-bits%n+n-1 > 0
> therefore bits-bits+n-1<0 is always false?
>
> So how can this loop ever iterate more than once as the documentation
> says it can.

Java int is 2's complement signed. If (n-1) and (bits-val) are both
large enough, their sum may wrap around to negative. Think of the "< 0"
test in the Java code as meaning, in mathematical integer arithmetic, ">
Integer.MAX_VALUE".

Patricia

Roedy Green
Guest
Posts: n/a

 01-04-2008
On Wed, 2 Jan 2008 21:16:00 -0800 (PST), (E-Mail Removed) wrote,
quoted or indirectly quoted someone who said :

>So how can this loop ever iterate more than once as the documentation

next and nextInt are quite different animals.
--
The Java Glossary
http://mindprod.com