views:

288

answers:

2

When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?

+5  A: 

Python's version is much faster in a simple test on my Mac:

jython -m timeit -s "import random" "random.random()"

1000000 loops, best of 3: 0.266 usec per loop

vs

 jython -m timeit -s "import java.util.Random; random=java.util.Random()" "random.nextDouble()"

1000000 loops, best of 3: 1.65 usec per loop

Jython version 2.5b3 and Java version 1.5.0_19.

Alexander Ljungberg
timeit, eh? I must remember that one!! +1
rq
timeit is one of those python 'batteries included' things. Not strictly necessary but so nice to have.
Alexander Ljungberg
+2  A: 

Java's Random class uses (and indeed must use by Java's specs) a linear congruential algorithm, while Python's uses Mersenne Twister. Mersenne guarantees extremely high quality (though not crypto quality!) random numbers and a ridiculously long period (53-bit precision floats, period 2**19937-1); linear congruential generators have well-known issues. If you don't really care about the random numbers' quality, and only care about speed, LCG is however likely to be faster exactly because it's less sophisticated.

Alex Martelli
Actually, according to some old benchmarks I did in the D programming language, the Mersenne Twister is faster, though it uses more memory. This is because the Mersenne twister avoids the division op that linear congruential needs. About the only good reasons to use linear congruential are if you have extreme memory constraints or if you only need a few random numbers and the time it takes to seed the generator is a bottleneck. (Linear congruential has a smaller state space so seeding is faster.)
dsimcha
Where do LCGs need a division? Most LCGs that are used somewhere use a power of two as their modulus (which makes finding suitable parameters harder but is considerably faster).
Joey
Java specifies a modulus of exactly (2**48)-1, and all Java standard implementation MUST use exactly that, so I don't see what "most LCGs that are used somewhere" have to do with the case -- java.Random has its own very precise rules.
Alex Martelli