[java] Probabilty Problem
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?
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.
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:
ps. floating point numbers do indeed have way more than 1001 possible values
//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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement