据我所知,在Java中,我可以使用以下代码生成一个随机数:
Random rand=new Random()
int x=rand.nextInt(1);
我有兴趣生成号码zero
或one
。但是我希望这个数字one
的生成概率比零高90%。
我怎样才能做到这一点?
感谢
编辑: 感谢大家。它正在发挥作用。
答案 0 :(得分:4)
生成0到9之间的随机数。如果数字为0,则返回零。如果数字是1-9,则返回一个。
答案 1 :(得分:2)
这是表达它的一种非常紧凑的方式
Random rand=new Random();
int x = ((rand.nextInt(10) == 0)) ? 0 : 1;
答案 2 :(得分:2)
这样就可以了:
int result;
if (Math.random() < 0.9) {
result = 1;
}
else {
result = 0;
}
或者更简洁:
int result = (Math.random() < 0.9) ? 1 : 0;
答案 3 :(得分:2)
阅读nextInt(int)手册,其中说:
从此随机数生成器的序列中返回一个伪随机,均匀分布的int值,介于0(包括)和指定值(不包括)之间。 nextInt的常规协定是伪随机生成并返回指定范围内的一个int值。所有n个可能的int值都以(近似)相等的概率产生。方法nextInt(int n)由Random类实现,如下所示:
将您的代码更改为
Random rand=new Random();
int x=rand.nextInt(10);
return (x == 0) ? 0 : 1;
,然后再次运行
答案 4 :(得分:0)
你可以这样写。
int x = (int) (Math.random() / 0.9); // 90% chance of 0
或
int x = (int) (Math.random() + 0.9); // 90% chance of 1