简体   繁体   中英

Generating a random number between 0 and x (Java)

Using the Xorshift random number generator... I already have the generator, but I haven't been able to modify it to give a number between 0 and an upper limit (like the nextInt() method in the Java Random class).

  long seed = System.nanoTime();

  int next(int nbits) {
    long x = seed;
    x ^= (x << 21);
    x ^= (x >>> 35);
    x ^= (x << 4);
    seed = x;
    x &= ((1L << nbits) -1);
    return (int) x;
  }

Any ideas?

you can see what java does withrandom class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM