Page 1 of 1

returning true or false based on a percentage chance

Posted: Mon Dec 17, 2007 5:27 pm
by Burrito
part of this method is randomness, but part needs to be a percentage chance to return true or false. I'm thinking the best way to do this is to try to add up to 100 and if my result is 100 or greater, then I return true else false.

I know that statement alone is extremely vague so let me try to spell it out a bit more:

I have a token that gives me a 50% chance to return true and one that gives me a 25% chance to return true. I think the way I want to handle this is to use a random number generator between 1 and 100. I then add the percent chance to that number and if it's greater than or equal to 100 it returns true, otherwise it returns false.

Can anyone else think of another / better way to handle a situation like this?

Burr

Posted: Mon Dec 17, 2007 5:36 pm
by John Cartwright
If I understood you correctly, this function will pass approximately 25% of the time.

Code: Select all

<?php

$pass = 0;
$fail = 0;
$chance = 25;

function checkRandom($chance)
{
   return rand(1,100) <= (int)$chance;
}

for ($x=0; $x < 100; $x++) {
	if (checkRandom($chance)) $pass++;
	else $fail++;
}

echo 'Passes: '. $pass .'<br>';
echo 'Fail: '. $fail;

?>

Posted: Mon Dec 17, 2007 5:38 pm
by pickle

Code: Select all

$tokens = array(50,25);

$total_chance_true = array_sum($tokens);
$random = rand(1,100);

if($random < $total_chance_true)
   return TRUE;
else
   return FALSE;
Or, to be a complete obfuscation junkie:

Code: Select all

$tokens = array(50,25);
return (rand(1,100) < array_sum($tokens))

DAMN: sniped by the `cart.