15

I need to generate a controlled sequence of pseudo-random numbers, given an initial integer parameter. For that I'm using the standard Java Random class, seeded by an integer parameter. I'd like to make sure that I will generate the same sequence across systems (Operating system, but also Java/JDK version), in the foreseeable future (and more!).

In summary: Does Java ensure the reproducibility / portability of it's pseudo-random number generator across implementation and versions?

Note: I've asked the exact same question for Python. I since changed the implementation language to Java but for other reasons.

Community
  • 1
  • 1
Laurent Grégoire
  • 4,006
  • 29
  • 52
  • 1
    it shall be fine as long as you don't reuse the same generator from multiple threads. Now don't get this comment wrong: the generator itself is thread-safe, but if you're generating numbers from various threads using the same generator, you would not be able to consistently reproduce the calls from your various threads in the exact same order on various systems (not even on various runs on the same system). – TacticalCoder Feb 05 '12 at 19:13
  • That will not be the case, but thanks for the tip. Well, to be precise, you can reproduce the same sequence within several threads using a proper locking mechanism, but I agree with you that's asking for trouble. – Laurent Grégoire Feb 27 '12 at 12:43

1 Answers1

15

Yes.

The javadoc explains:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245