I am trying to create a randomness script that increases the chances of returning true with every day that passes.
For example on January 1st, the odds should be roughly 1:12 of getting true
On December 31st the odds should be 1:1 of getting true.
My first attempt at the script simply used date(‘F’) – 12 and used abs() to reverse any negative. However this resulted in an obvious jump in chance every month. I would instead like to increase the chance daily (or even by the second if possible).
This is what I’ve come up with, but I’m not sure if my logic is right and if there is a better way:
$day = date("z");
$max = abs($day - 365)/30;
$rand = rand(0,$max);
if ($rand == 0)
{
return true;
}
4
Answers
You can use unix timestamp of two dates, than you will have precision in seconds.
Your current solution assumes that
rand()
can work with floats, it doesn’t.What you can do is compute the number of seconds in a year and use that to determine the chance:
Live demo: https://3v4l.org/IOu5D
So here the
rand()
function picks a random second for a whole year, and then checks this against$changeLimit
. In the beginning of the year$changeLimit
will have 1 month worth of seconds, so the change to be TRUE will be 1/12, and at the end of the year it will have half a years worth of seconds, with a change of 1/2.This all allows for precise control of the chance at the beginning and the end of the year.
You can, of course, make this code a lot shorter by not using all those variables, but I think it is needed here to explain what’s going on.
You also don’t have to do this to the second, as you wanted, because if you do it by day it will have the same result:
Live demo: https://3v4l.org/nlrhk
Here is a solution that computes the probability (
$prob
) for the current timestamp ($t
):$t0
is the timestamp of the beginning of the year.$t1
is the timestamp of the end of the year.If
$t
is equal to$t0
(we are at the beginning of the year), the probability is 1/12.If
$t
is equal to$t1
(we are at the end of the year), the probability is 1.The probability increases linearly from 1/12 to 1.
lcg_value()
draws a random float between 0 and 1.Here is a function that calculates the probability using the day of the year. The function accepts an optional
dateString
as argument.and here some testcode: