问题描述
我很好奇,我该如何在Java中实现概率?例如,如果变量显示的机会是1/25,那么我将如何实现呢?还是其他可能性?请指出我的大致方向.
I was curious to know, how do I implement probability in Java? For example, if the chances of a variable showing is 1/25, then how would I implement that? Or any other probability? Please point me in the general direction.
推荐答案
您将使用随机生成一个随机数,然后根据文字对其进行测试,以匹配您尝试达到的概率.
You'd use Random to generate a random number, then test it against a literal to match the probability you're trying to achieve.
所以给定了:
boolean val = new Random().nextInt(25)==0;
val
的概率为1/25(因为nextInt()
的概率为返回从0到25(但不包括25)的任何数字).
val
will have a 1/25 probability of being true (since nextInt()
has an even probability of returning any number starting at 0 and up to, but not including, 25.)
您当然也必须import java.util.Random;
.
如下所述,如果您获得多个随机数,则重用Random对象而不是始终重新创建它会更有效:
As pointed out below, if you're getting more than one random number it'd be more efficient to reuse the Random object rather than recreating it all the time:
Random rand = new Random();
boolean val = rand.nextInt(25)==0;
..
boolean val2 = rand.nextInt(25)==0;
这篇关于Java中的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!