[java] Probabilty Problem

Started by
9 comments, last by Thygrrr 19 years, 5 months ago
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?
"..."
Advertisement
Quote:Original post by Nomad010
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?


"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.
Call Java's random function, and if the return value is 1 million, set your bool to true. Otherwise, set it to false.
Java's Math.random function only produces a random number from 0.000 to 1.000. There are only 1001 possibilities.
"..."
That's a floating point number, so if((int)(Math.random()*1000000.0) == 1000000)
Quote:Original post by Nomad010
Java'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.
Don't use Math.random, use java.util.Random, and call nextInt(). The code looks like this:

//create the random, note how we seed itRandom r = new Random(System.currentTimeMillis());// ....boolean bOneInAMillion = (r.nextInt() % 1000000) == 0;


ps. floating point numbers do indeed have way more than 1001 possible values
Oops. I was confusing the Math.random() function for another class. *cough*.

Ratings++ for tombr and Thex0.
"..."
lol, tombr and Thex0 are still at 1000, I don't think he knows what "Ratings++" means
Yeah. We all have 1000 ratings so it doesn't really do anything.
"..."

This topic is closed to new replies.

Advertisement