Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2008

Tip: Looking for answers? Try searching our database.

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

Thread view: 
tyrandor3@gmail.com - 03 Jan 2008 05:16 GMT
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.
Patricia Shanahan - 03 Jan 2008 06:28 GMT
> reference
> http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
[quoted text clipped - 17 lines]
> 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 - 04 Jan 2008 03:25 GMT
>So how can this loop ever iterate more than once as the documentation

next and nextInt are quite different animals.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.