I’ve generated a series of random numbers from a known seed in C using srand() and rand() from stdlib. I now need to generate the same series of numbers using the same seed from C in Java.
Java’s Random class documentation states it uses a “linear congruential formula”. The documentation I’ve found on rand() says it uses a “linear congruential” generator, although I’m not sure if this is for one specific implementation.
Does anyone know if both generators will produce the same numbers if given the same seed or if a port of srand() and rand() exists for Java?
The C standard does not dictate the implementations of srand() and rand(). As such, different environments (OS, C libraries, architecture, etc.) will more than likely produce sequences of numbers that are different for the same seed value.
Also, the implementation Java’s Random class is not bound to any particular algorithm. Here again, different JVMs may very well produce different sequences for the same seed value. In addition, the implementation will more than likely not be tied to the standard C functions. Which means, the Java produced sequence will be different than a C sequence using the same seed.
If you truly need to generate random sequence in Java to match exactly that of the standard C functions, the best you could hope to do is replicate the sequence for a particular environment. This would require creating a JNI library to proxy calls to srand() and rand() or creating some other external process that makes the calls and is invoked from Java. Either way, that’s a lot of complexity and more program maintenance.
If in fact all you need are random sequences that appear to be uniformly distributed, regardless of the exact values, then use Random as is. It is more than sufficient for most RNG needs.