Redian新闻
>
java 随机数 nextInt(int n)的问题
avatar
java 随机数 nextInt(int n)的问题# Java - 爪哇娇娃
b*y
1
jdk里面的源程序如下:
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
读不懂的地方是while(bits - val + (n-1) < 0);
为啥要这样判断呢?
avatar
c*t
2
javadoc 里面写着呢:
*
* The loop at the bottom only accepts a value, if the random
* number was between 0 and the highest number less then 1<<31,
* which is divisible by n. The probability for this is high for small
* n, and the worst case is 1/2 (for n=(1<<30)+1).
*

【在 b******y 的大作中提到】
: jdk里面的源程序如下:
: public int nextInt(int n) {
: if (n<=0)
: throw new IllegalArgumentException("n must be positive");
: if ((n & -n) == n) // i.e., n is a power of 2
: return (int)((n * (long)next(31)) >> 31);
: int bits, val;
: do {
: bits = next(31);
: val = bits % n;

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。