returning true or false based on a percentage chance

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

Post Reply
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

returning true or false based on a percentage chance

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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;

?>
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply