Jump to content

Probability of an action happening in PHP.


Go to solution Solved by PhpNewb314,

Recommended Posts

I wonder how I can execute an action which has x% chance of happening, for instance a 31% chance of happening. How would I do that? I was thinking of using rand() to generate a number between 1 and 100 and if it is <= 50 (or whatever the percentage is, since that is going to vary based on the rank of the individual and hopefully fluctuate within ranks) then it is successful and if it is >50 then it isn't successful. 

 

 

This is just a preliminary idea and is definitely going to get more complex since I need to vary the percentage depending on rank and even slight fluctuation within rank (it is a game) but I was wondering about the best way to do this aspect of it. Is this the best way or is there a more efficient (or more elegant) way?

 

Thanks for any advice!

  • Solution

that's how you do it, yes.

 

function probability($p) {
  return $p >= rand(1,100);
}

if ( probability(31) )
  echo 'true';
else 
  echo 'false';

I thought that was probably the best way. Thank-you for confirming this, Josh!

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.