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

Discussion in 'Java' started by tyrandor3@gmail.com, Jan 3, 2008.

  1. Guest

    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.
     
    , Jan 3, 2008
    #1
    1. Advertising

  2. wrote:
    > 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
     
    Patricia Shanahan, Jan 3, 2008
    #2
    1. Advertising

  3. Roedy Green Guest

    On Wed, 2 Jan 2008 21:16:00 -0800 (PST), 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.
    --
    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Jan 4, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Elmar Baumann
    Replies:
    0
    Views:
    638
    Elmar Baumann
    Feb 2, 2004
  2. Schnoffos
    Replies:
    2
    Views:
    1,252
    Martien Verbruggen
    Jun 27, 2003
  3. Hal Styli
    Replies:
    14
    Views:
    1,712
    Old Wolf
    Jan 20, 2004
  4. Sakagami Hiroki

    java.util.Random.nextInt() thread safety

    Sakagami Hiroki, Aug 29, 2006, in forum: Java
    Replies:
    5
    Views:
    10,148
    Eric Sosman
    Aug 29, 2006
  5. briteguy
    Replies:
    10
    Views:
    5,731
    John B. Matthews
    Mar 18, 2009
Loading...

Share This Page