# [java] Probabilty Problem

This topic is 5058 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

While doing work on a game, I came across a problem where I needed to a boolean that was true only 1 millionth of the time. Does anyone know of any Java code or classes available to allow me to do that?

##### Share on other sites
Quote:
 Original post by Nomad010While doing work on a game, I came across a problem where I needed to a boolean that was true only 1 millionth of the time.Does anyone know of any Java code or classes available to allow me to do that?

"I needed to a boolean"

What do you mean by this? It might have just been a typo, but please fix it so we know what you mean and can help.

##### Share on other sites
Call Java's random function, and if the return value is 1 million, set your bool to true. Otherwise, set it to false.

##### Share on other sites
Java's Math.random function only produces a random number from 0.000 to 1.000. There are only 1001 possibilities.

##### Share on other sites
That's a floating point number, so if((int)(Math.random()*1000000.0) == 1000000)

##### Share on other sites
Quote:
 Original post by Nomad010Java's Math.random function only produces a random number from 0.000 to 1.000. There are only 1001 possibilities.

Why do you think that. It says nothing about this in the javadoc. I don't know how many bits of precision you get, but it is defenitly more than you need.

##### Share on other sites
Don't use Math.random, use java.util.Random, and call nextInt(). The code looks like this:

//create the random, note how we seed it
Random r = new Random(System.currentTimeMillis());

// ....

boolean bOneInAMillion = (r.nextInt() % 1000000) == 0;

ps. floating point numbers do indeed have way more than 1001 possible values

##### Share on other sites
Oops. I was confusing the Math.random() function for another class. *cough*.

Ratings++ for tombr and Thex0.

##### Share on other sites
lol, tombr and Thex0 are still at 1000, I don't think he knows what "Ratings++" means

##### Share on other sites
Yeah. We all have 1000 ratings so it doesn't really do anything.

1. 1
2. 2
Rutin
22
3. 3
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
632566
• Total Posts
3007107

×