Jump to content

php rand and percentage


zero_ZX
Go to solution Solved by zero_ZX,

Recommended Posts

Hi,

 

I basically want a function that takes a parameter which is a percentage chance of the functioning returning true.

A user can move from tier 1->10 and at tier 1 there's a 70% chance to move to tier 2, from tier 2 there's a slightly less chance to move up, and so on.

 

I tried with the following piece of code:

 

 

public function rollTheDice($winnerPercentage)
{
$number = rand(1, 100);
if ($number <= $winnerPercentage)
return true;
return false;
}

 

The above code makes logical sense to me:

1. Pick a random number between 1 and 100.

2. If that number is less than or equal to the percentage, then we passed (example, if the random number is less than or equal to 70.. there must be a 70% chance of this?)

 

This however does not seem to work, in fact it appears that when simulating a roll, 70% fails at the very first step (where there is a 70% chance of winning..)

To actually make it to tier 10, has yet to be accomplished, so by simulating this with unlimited attempts for 120 seconds straight doesn't seem to "win".

 

I tried (just for fun) and change the if-statement so:

if ($number >$winnerPercentage)

 

This seems to be working quite well, as the simulator quickly reaches tier 10 this way.

Any suggestions to code changes, or can someone explain why it is working way better when exchanging less than with greater than?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.