Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

Probability in Java

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.

question from:https://stackoverflow.com/questions/8183840/probability-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'd use Random to generate a random number, then test it against a literal to match the probability you're trying to achieve.

So given:

boolean val = new Random().nextInt(25)==0;

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.)

You would of course have to import java.util.Random; as well.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...