java 在 Math.random() 上设置种子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2836718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:05:24  来源:igfitidea点击:

Set seed on Math.random()

javarandomrandom-seed

提问by Kevin

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

我需要对调用Math.random(). 我知道如果我正在实例化我自己的 Random 对象以产生可重复的结果,我可以设置种子。有没有办法做到这一点Math.random()

回答by rsp

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

该方法Math.random()使用私有静态字段:

private static Random randomNumberGenerator;

If you really reallyneed 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.

如果您真的需要将其设置为 a new Random(CONSTANT_SEED)(例如您需要 JUNit 测试您无法控制的代码),您可以使用反射来实现

回答by Jonathan M Davis

How about creating an instance of Randomyourself 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 Randomand use it directly, however, you can set the seed for that when you create it, and/or you can call setSeed()on it later.

创建一个Random自己的实例并使用它怎么样?Math.random()创建一个并使用它,所以我认为你不会弄乱它的种子。Random但是,如果您创建并直接使用它,您可以在创建它时为其设置种子,和/或您可以setSeed()稍后调用它。

回答by iTake

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

使用带有种子的 Random 实例设置它,或者只是扩展方法以返回您需要的值

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

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

        });