Lottery algorithm - PHP - math seems good, but is the function valid? -
i want make custom lottery extraction motivate users participate in online experiment. rules are:
- 10% 10$
- 1% chance 50$
- 0.1% chance 500$
the lottery php function gets called once , returns prize (0, 10, 50 or 500). created function below, , after 70 000 trials statistics are:
- 9.11% 10$
- .91% 50$
- .01% 500$
should worried algorithm? there better way create distribution of chances mt_rand ?
function lottery() { // winnings before extraction $win=0; // choose winning number between 1 , 10 $target=mt_rand(1,10); // make 3 independent extractions, each 1/10 probability if (mt_rand(1,10) == $target) { // if first extraction winning number -> prize=10 // probability: 1/10 $win=10; if (mt_rand(1,10) == $target) { // if second extraction winning number -> prize=50 // probability: 1/10 * 1/10 $win=50; if (mt_rand(1,10) == $target) { // if third extraction winning number -> prize=500 // probability: 1/10 * 1/10 * 1/10 $win=500; } } } // return prize return $win; }
thank helping newbie!
you have 4 outcomes given probabilities:
- 0.1% probability win $500.
- 1% probability win $500.
- 10% probability win $500.
the fourth outcome - no win - 100% minus sum of other 3 outcomes, namely 88.9%.
mark gabriel has explained why initial code off: promoting 10% of people have won $10 $50 winners, take them away pool of $10 winner, 9% of people.
pham trung has contributed solution takes winners of higher amounts pool of non-winners far , adjusts probabilities. that's workable solution, easiest solution in opintion call random number generator once.
this solution reflects ticket analogy best: place 10,000 tickets in box. 1,000 tickets 1 1000 win $10. 100 tickets 1001 1100 win $50. ten tickets 1101 1110 win $500. 8890 tickets 1111 on don't win anything:
function lottery() { var pick = math.floor(10000 * math.random()); // random number in range [0, 10000). if (pick < 1000) return 10; if (pick < 1100) return 50; if (pick < 1110) return 500; return 0; }
in code, tickets have number written on them. pick one. check whether ticket number eligible $10. if not, check same ticket whether may bet $50 win. there 1 random action involved.
(i've used zero-based random-number function in javascript instead of php's mt_rand
, think solution clear.)
Comments
Post a Comment