Generating a random number between 0 and x (Java)

Go To StackoverFlow.com

4

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?

2012-04-04 19:21
by ppepper
Can you use ((int)x) % (upper_limit + 1)? (That's a sincere question; I don't know enough about the properties of Xorshift -- specifically, about how much entropy it has in the lower bits -- to know if that's a good idea. - ruakh 2012-04-04 19:23
Use the remainder function - n % - Gilbert Le Blanc 2012-04-04 19:24
I thought about this but I had a feeling it would affect the cryptographic strength. Is there no reason why it should have any effect on it - ppepper 2012-04-04 19:27


4

you can see what java does with random class

2012-04-04 19:26
by dash1e
The OP is aware of this class, since they mentioned it in the question - Paul Bellora 2012-04-04 19:28
I know, but I believe the OP never read the source code of that class or he would been able to solve the problem. So I link the sources - dash1e 2012-04-04 19:37
@PaulBellora: But (s)he may not have been aware that there's an open-source implementation of that class. (Note that this answer links directly to source-code. - ruakh 2012-04-04 19:37
@ruakh correct, and in that source file there are also clear comments and explanation about that task - dash1e 2012-04-04 19:42
Okay, both fair enough points - Paul Bellora 2012-04-04 19:52
Ads