PhpNewb314 Posted March 9, 2014 Share Posted March 9, 2014 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! Link to comment https://forums.phpfreaks.com/topic/286836-probability-of-an-action-happening-in-php/ Share on other sites More sharing options...
.josh Posted March 9, 2014 Share Posted March 9, 2014 that's how you do it, yes. function probability($p) { return $p >= rand(1,100); } if ( probability(31) ) echo 'true'; else echo 'false'; Link to comment https://forums.phpfreaks.com/topic/286836-probability-of-an-action-happening-in-php/#findComment-1471937 Share on other sites More sharing options...
PhpNewb314 Posted March 9, 2014 Author Share Posted March 9, 2014 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! Link to comment https://forums.phpfreaks.com/topic/286836-probability-of-an-action-happening-in-php/#findComment-1471938 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.