Pentrophy
Pentrophy

Reputation: 79

75% probability in Java

How would I go about implementing a 3/4 or 75% probability using this format in java?

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

Upvotes: 0

Views: 8017

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Something like this,

Random rand = new Random();
int val = rand.nextInt(4) + 1;
if (val == 1) { // <-- 1/4 of the time.
} else { // <-- 3/4 of the time.
}

Random.nextInt(int) returns Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). So, to 0-4 (exclusive) is (0-3) and if you then add 1 the result is the range (1-4).

You might also use Random.nextDouble() like,

if (rand.nextDouble() < 0.75) { // <-- 75% of the time.
}

Upvotes: 8

user11417454
user11417454

Reputation:

The following is also valid and somewhat intuitive since many people share the notion of probability as being a value between 0 and 1:

Math.random() < 0.75

Of course, this is the same as

Random rand = new Random();
rand.nextDouble() < 0.75

which has been mentioned in the accepted answer.

One important point to note though is that the latter is more efficient than the former. Pete provides an explanation of why this the case on Oracle's community forum.

Upvotes: 1

Eric
Eric

Reputation: 19863

Try this :

rand.nextInt(4) < 3

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47729

A simple-minded way to do it that is good for any integer percent is:

boolean val = rand.nextInt(100) < 75;

Upvotes: 6

Related Questions