问题
Currently I'm using a uniform distribution to generate a winning probability.
For a probability of let's say 1%
I define a winning number 47
then I do a mt_rand(1,100)
and if the number is 47
the user win. Which is fine.
This work well for small probability like 1/100'000
but when I want a probability of let's say 40%
which is 1/0.4 = 2.5
I cannot make mt_rand(1,2.5)
I have to do mt_rand(1,2)
or mt_rand(1,3)
which mean respectively 50%
and 33%
.
How should I do to get a 40%
probability?
回答1:
if (mt_rand(1, 100) / $probability <= 1) {
// success
}
E.g. if you have now $probability = 10
; you have ten (of hundred) cases where the number between 1 and 100 is smaller or equal to one.
回答2:
let's say you want winning probability as x (assuming an integer), then generate
$num = mt_rand (1,100)
if ($num<=$prob) {//user wins}
If you don't have $prob as an integer and is a number with 2 decimal places eg: 47.23%, then you could generate
$num = mt_rand(1,10000)
if ($num/100 <= $prob), {//user wins}
Similarly you can extend it to whatever accuracy you want
来源:https://stackoverflow.com/questions/17171896/uniform-distribution-in-a-small-range-to-generate-precise-big-probability