Page 1 of 1

Will This Work (Random event.)

Posted: Tue Mar 27, 2012 3:31 pm
by narcah
I'm working on a WordPress plugin and I only want it to show once in a great long while. It's a popup message at the bottom of the screen. Will this work?

$r=rand(1,100);
if ($r != 44)
{
die();
}

Basically, I'm making a random number, if the random number is not equal to 44 (it could be any number between 1 and 100) then it kills the script. I could test it, but it has a 3 second delay, and 1 in 100 chances are pretty hard to come by. :)

Thanks!

Re: Will This Work (Random event.)

Posted: Tue Mar 27, 2012 4:34 pm
by social_experiment
narcah wrote:and 1 in 100 chances are pretty hard to come by
Since the number is being picked randomly and not in any sequence you can't say that the time taken before 44 is reached is fixed. A timer will be a better option if you are looking for a action to occur after a certain time.

You can test this for yourself by running a for loop x amount of times to see the results;

Code: Select all

<?php
 $t = 100;
 //
 for ($i=0;$i<$t;$i++) { 
     $r = rand(1, 100);	 
     echo ($r != 44) ? $r . ' ' : '44 found ';     
 } 
?>
Results of running the script twice; 44 will pop up more unexpectedly than you wish

Code: Select all

44 found 18 37 94 77 41 80 58 43 1 80 16 19 9 84 31 31 75 58 11 57 66 91 63 43 86 78 59 48 13 53 18 59 50 47 19 28 2 27 52 50 77 68 66 26 97 95 39 4 5 77 52 66 9 16 11 31 59 43 88 52 77 70 66 30 13 94 39 97 78 62 60 77 79 19 98 36 83 15 52 79 73 47 100 9 29 54 53 99 38 41 31 69 32 56 58 50 64 80 17 
//
97 62 72 42 9 20 95 24 64 62 17 52 81 98 23 70 89 39 21 42 63 39 19 86 3 35 51 96 27 98 41 57 59 43 47 42 15 55 18 42 74 58 71 12 59 65 44 found 2 46 37 65 92 37 88 34 69 44 found 72 67 67 11 73 22 26 13 58 11 33 49 95 93 7 25 68 2 48 41 3 75 25 21 82 51 22 98 65 18 57 92 85 99 93 95 39 78 22 27 90 96 16 
If you want the event to happen unexpectedly then this is the way to go

Re: Will This Work (Random event.)

Posted: Tue Mar 27, 2012 5:24 pm
by narcah
That's about the right amount, thanks!

Re: Will This Work (Random event.)

Posted: Wed Mar 28, 2012 2:22 am
by requinix
social_experiment wrote:Results of running the script twice; 44 will pop up more unexpectedly than you wish
And that there touches on the difference between randomness and infrequency. Random is random: it's possible (though unlikely) that 44 will come up twice in a row. The first roll has nothing to do with the second. If that shouldn't happen then simply "random" isn't enough and there'd have to be a second criteria or rule in the mix.

For instance, "randomly... but always within 100 minutes of the last time". This is pretty easy to do with

Code: Select all

(rand() / getrandmax()) <= (time elapsed since the last time it happened / 100 minutes)
Or there's "randomly... within the next 100 instances", which basically means picking a random number X between 1 and 100 and waiting for the Xth instance.