//randomBounds.java
//Does Math.random() produce 0.0 and 1.0?
//=========================================
//此Demo是Bruce Eckel在书中提供的测试random()是否产生
//0.0和1.0的方法,作者采用依次比较的方法,但实际上,如果
//random()产生的随机数一直不是0.0或1.0(先假设它可以产生这两个
//边界值)的话,那程序就会一直运行下去而无法判断是否会包含边界值
//因此,这种方法是不保险的。
//-------------------------------------------《Thinking in Java》p132
//=========================================
public class randomBounds
{
static void usage()
{
System.out.println("Usage /n/t"
+ "randomBounds lower/n/t"
+ "randomBounds upper");
System.exit(1);
}
public static void main(String[] args)
{
if(args.length != 1)
usage();
if(args[0].equals("lower"))
{
while(Math.random() != 0.0)
;//Keep trying, until get 0.0
System.out.println("Produced 0.0!");
}
else if(args[0].equals("upper"))
{
while(Math.random() != 1.0)
;//Keep trying, until get1.0
System.out.println("Produced 1.0!");
}
else
usage();
}
}//end of class randomBounds
博客围绕Java中测试Math.random()是否产生0.0和1.0边界值展开。介绍了Bruce Eckel在《Thinking in Java》中采用依次比较的测试方法,但指出若随机数一直不是边界值,程序会一直运行,该方法不保险,并给出了相应代码示例。
936

被折叠的 条评论
为什么被折叠?



