How To Implement Small Probabilities In Java
Hi,
i need to remove strings in an ArrayList<String> by a small random probability (10^-7). My idea was to set a boolean if the string must be removed, that boolean should be false. So i wrote following code
public boolean shouldSequenced() {
boolean decision = false;
double prob = Math.random();
if (prob > Math.pow(10, -7)) {
decision = true;
}
return decision;
}
My problem is now that Math.random() generates always numbers higher than 10^-7 so i will never set the boolean to false. And if i multiply "prob" with 10^-7 i will be always smaller than 10^7 and would set my boolean always false. Has anyone an idea how to solve this?
Thanks in advance for your help.
• 3,046 views
•
link
0 answers
No answers yet.
Log in to answer this question.
see java.util.Random return rand.nextDouble() < 1E-7 ;
"My problem is now that Math.random() generates always numbers higher than 10^-7" note that your statement is nonsense, the probability is simply very low (~10^-7, actually a tiny bit higher). If you generate enough randoms you will surely see such.
it could also be "actually a tiny bit smaller even" depending on the algorithm, (the lower tail between min.double and 0 might be missing)