由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Java版 - java 随机数 nextInt(int n)的问题
相关主题
java里的时间计算eclipse怎么无法成功导出jar文件的?
very weird problem初学Java, FormLayout一问
ERROR!java.io.RandomAccessFile.readInt请推荐java高阶用书
java source code analyzing toolJava 8 stream 可以 代替 do while loop吗?怎么写
Java都在什么时候进行Garbage collection?跪求大牛指点Java,看不懂什么意思。
java为啥这么多framework问个简单的Java技术问题
如何生产产生Java Doc的注释Ask a simple question about throw exception, bow bow bow
Sun Java 被 Oracle 收购后,help: cannot generate index.html using javadoc
相关话题的讨论汇总
话题: bits话题: val话题: int话题: nextint话题: 31
进入Java版参与讨论
1 (共1页)
b******y
发帖数: 9224
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);
为啥要这样判断呢?
c*****t
发帖数: 1879
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;

1 (共1页)
进入Java版参与讨论
相关主题
help: cannot generate index.html using javadocJava都在什么时候进行Garbage collection?
Mini Javadoc Howto -- Re: help: cannot generate index.html using javadocjava为啥这么多framework
JDK Source?如何生产产生Java Doc的注释
How to append something on a file?Sun Java 被 Oracle 收购后,
java里的时间计算eclipse怎么无法成功导出jar文件的?
very weird problem初学Java, FormLayout一问
ERROR!java.io.RandomAccessFile.readInt请推荐java高阶用书
java source code analyzing toolJava 8 stream 可以 代替 do while loop吗?怎么写
相关话题的讨论汇总
话题: bits话题: val话题: int话题: nextint话题: 31