Calling a Method 1 out of 100 Times
Question
I need a 1 in a 100 chance of some functionality being called. Right now I am using the following code, but it's being called more often than 1% of the time.
int randomItem = (int)(Math.random()*100);
if (randomItem >= 90 && randomItem <= 100)
{
// Do something ...
}
Solution
You're adding the sprite when the random number is between 90 and 100. This makes a 10% chance. Just test if Math.random() is < 0.01
.
OTHER TIPS
You have to say something like if (Math.random() * 100 >= 99.0)
, or just without the scaling, if (Math.random() >= 0.99)
, or with the integer, if (randomItem == 99)
.
Math.random()
returns a floating point number in the range [0.0, 1.0)
, so 100 times this gives you a range [0.0, 100.0)
, and conversion to integer gives an integer in the range [0, 100)
.
The conversion to integer may not be necessary if you don't need it for anything else.
You should replace
randomItem >= 90 && randomItem <= 100
with
randomItem == 99
Right now you have a 1 int 10 chance. To get a 1 in 100 chance do this:
int chance = (int)(100*Math.random())
if (chance == 1) {
//Code
}
Math.Random
returns a number between 1 and 0. To get a 1% chance you want your code to look somewhat like this:
Math.Random() <= 0.01
Also, the nextDouble
method of the Random
class is used the same way.
r.nextDouble() < 0.01; //r is a instance of Random
Both of these will give you a 1% chance.