Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set seed on Math.random()

I need to write some junit tests on Java code that calls Math.random(). I know that I can set the seed if I was instantiating my own Random object to produce repeatable results. Is there a way to do this also for Math.random() ?

like image 216
Kevin Avatar asked May 14 '10 18:05

Kevin


2 Answers

The method Math.random() uses a private static field:

private static Random randomNumberGenerator;

If you really really need to set this to a new Random(CONSTANT_SEED) (for instance you need to JUNit test code which you have no control over) you could do so by using reflection.

like image 57
rsp Avatar answered Oct 21 '22 02:10

rsp


How about creating an instance of Random yourself and using that instead? Math.random() creates one and uses that, so I don't think that you can mess with its seed. If you create a Random and use it directly, however, you can set the seed for that when you create it, and/or you can call setSeed() on it later.

like image 44
Jonathan M Davis Avatar answered Oct 21 '22 01:10

Jonathan M Davis