Uniform distribution in a small range to generate precise big probability

旧时模样 提交于 2019-12-13 04:30:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!