how doas the algorithm of random number work?

in class Random ,the method nextInt:

public int nextInt(int n) {

if (n<=0) throw new IllegalArgumentException("n must be positive");

if ((n & -n) == n) // i.e., n is a power of 2

return (int)((n * (long)next(31)) >> 31);

int bits, val;

do {

bits = next(31);

val = bits % n;

} while(bits - val + (n-1) < 0);

return val;

}

I don't understand the idea, but I would like to have it understood.

thanks a lot, Meir!

[511 byte] By [038790804] at [2007-9-27 20:59:07]
# 1

Make a good random generator is not an easy task. It should pass lots of tests to asure that the numbers that are generated are as "random" as they can be (they should not repeat, etc).

If you want to learn exactly how the algorithm in the class random works and why it is good you should read the book from where it was taken. If i can remember the API documentation says where the algorithm comes. Probably the book will not anly tell you about the algorithm itself but why does it works and how.

Just look for it.

Hope this helps.

Zerjillo

Zerjio at 2007-7-7 2:39:25 > top of Java-index,Other Topics,Algorithms...
# 2

> I don't understand the idea, but I would like to have

> it understood.

Hopefully you then have a strong background in theoretical math concepts because you will need it to understand how random number generators correctly work (at least for that particular one you will.)

As mentioned the java API docs for that class specifically point you to the reference - See Donald Knuth, "The Art of Computer Programming, Volume 2".

jschell at 2007-7-7 2:39:25 > top of Java-index,Other Topics,Algorithms...
# 3
thank you guys, it's probably not as easy as I thoght.Meir.
038790804 at 2007-7-7 2:39:25 > top of Java-index,Other Topics,Algorithms...