Bad documentation on java.util.Random#nextInt(int)

P

Patricia Shanahan

reference
http://java.sun.com/javase/6/docs/api/java/util/Random.html#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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top