如何使用Java中的Math.random()以相等的概率生成随机数 [英] How do you generate a random number with equal probability using Math.random() in Java
本文介绍了如何使用Java中的Math.random()以相等的概率生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在练习中,我需要生成一个随机数,该随机数可以是4个值之一.(请注意,我只能使用Math.random())
I'm currently working through an exercise where I am required to generate a random number which can be one of 4 values. (note I'm only allowed to use Math.random())
01个2个或3
当前我正在使用: randno =(int)(Math.random()* 4);//范围为0-3
但是,结果必须具有相等的概率.到目前为止,我的测试(尽管缺少该方法)显示3出现的次数远少于其他数字.
However, the outcome MUST have equal probability. My tests so far (although the method is lacking) shows that 3 occurs far less than the other numbers.
这是巧合吗?还是我的发电机没有相等的概率.
Is this coincidence? Or does my generator not have equal probability.
谢谢!
推荐答案
您的代码运行良好:
public static void main(String[] args) {
int countZero = 0;
int countOne = 0;
int countTwo = 0;
int countThree = 0;
for(int i=0; i<400000; i++){
int randno = (int)(Math.random() * ((3) + 1));
if(randno == 0){
countZero++;
}
else if(randno == 1){
countOne++;
}
else if(randno == 2){
countTwo++;
}
else if(randno == 3){
countThree++;
}
}
System.out.println("Zero: " + countZero);
System.out.println("One: " + countOne);
System.out.println("Two: " + countTwo);
System.out.println("Three: " + countThree);
}
输出:
Zero: 99683
One: 99793
Two: 100386
Three: 100138
这篇关于如何使用Java中的Math.random()以相等的概率生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文