在Java中的范围内统一生成安全随机数 [英] Generate secure random number uniformly over a range in Java

查看:1014
本文介绍了在Java中的范围内统一生成安全随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

java.security.SecureRandom 似乎提供范围 0..2 ^ n

推荐答案

你可以做到

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

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

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

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.

这篇关于在Java中的范围内统一生成安全随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆