Set seed on Math.random()

孤人 提交于 2019-12-21 10:15:59

问题


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() ?


回答1:


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.




回答2:


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.




回答3:


Set it with instance of Random with your seed or just extend the methods to return values you need

        Field field = Math.class.getDeclaredField("randomNumberGenerator");
        field.setAccessible(true);
        field.set(null, new Random() {

            @Override
            public double nextDouble() {
                return 1;
            }

        });


来源:https://stackoverflow.com/questions/2836718/set-seed-on-math-random

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!