java 用Java在一定范围内均匀生成安全随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28742702/
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-11-02 14:06:37  来源:igfitidea点击:

Generate secure random number uniformly over a range in Java

javasecurityrandom

提问by anoopelias

How do I generate a secure uniformrandom number within a range? The range could be between 0 to 100. (The upper bound is not a power of 2).

如何在一个范围内生成一个安全的统一随机数?范围可以在 0 到 100 之间。(上限不是 2 的幂)。

java.security.SecureRandomseems to provide the range 0..2^n.

java.security.SecureRandom似乎提供了 range 0..2^n

回答by Peter Lawrey

You can do

你可以做

Random rand = new SecureRandom()
// 0 to 100 inclusive.
int number = rand.nextInt(101);

or

或者

// 0 inclusive to 100 exclusive.
int number = rand.nextInt(100);

Note: this is more efficient than say (int) (rand.nexDouble() * 100)as nextDouble() needs to create at least 53-bits of randomness whereas nextInt(100) creates less than 7 bits.

注意:这比(int) (rand.nexDouble() * 100)因为 nextDouble() 需要创建至少 53 位随机性而 nextInt(100) 创建少于 7 位的说法更有效。

回答by Snehal Patel

Try below code snap

尝试下面的代码快照

    SecureRandom random = new SecureRandom();

    int max=50;
    int min =1;

    System.out.println(random.nextInt(max-min+1)+min);