Playing the lottery

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Ah yes. This method is much more suitable for small probabilites.
And it doesn't need bcmath (the main reason why my naive attempt is so slow)
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

volka wrote:Ah yes. This method is much more suitable for small probabilites.
And it doesn't need bcmath (the main reason why my naive attempt is so slow)
Well thanks for the input anyway. I think my biggest problem is I don't know maths very well so when someone posted a formula 49!/6! I didn't understand what it meant. Once I realised what that (and a few other things) meant all the pieces started to fall into place. I changed the code a little bit now. I added the possibility to work out probabilities for minor wins too and another function that works out the bonus ball.

Code: Select all

function Probability($N, $m, $n = null)
{
    if(is_null($n)) return 1/ComputeOdds($N, $m);
    if($n>$m||$m>$N) return 0;
    return 1/(ComputeOdds($N, $m)/(ComputeOdds($m, $n)*ComputeOdds($N-$m, $m-$n)));
}

function ComputeOdds($d, $n)
{
    if($d<$n||$n<1) return 0;
    $r = 1;
    while($n&&$r*=$d--/$n--);
    return $r;
}

function NumPlays($prob, $percent)
{
    if($prob == 1) return 1;
    return intval(log(1-($percent/100))/log(1-$prob)+1);
}

echo '<p>Number of plays before reaching 50% probability of a minor win (3 balls): '.
      number_format(NumPlays(Probability(49, 6, 3), 50));
Post Reply