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;
}
Here is a function that calculates the probability using the day of the year. The function accepts an optional dateString
as argument.
function randomBooleanByDate($datestring = null) {
$currentDate = new DateTime($datestring);
$year = (int)$currentDate->format('Y');
// Get the day of the year (1 for Jan 1st, 365 or 366 for Dec 31st)
$dayOfYear = (int)$currentDate->format('z') + 1; // 'z' gives 0-based day of year, so +1
// Set the minimum and maximum probabilities (January 1st: ~1/12 or 8.33%, December 31st: 1/2)
$minProbability = 1 / 12; // About 8.33%
$maxProbability = 0.5; // 50%
// Calculate the current probability based on the progress of the year
$currentProbability = $minProbability + ($maxProbability - $minProbability) * ($dayOfYear / 365);
// Scale probability to a 1-1000 range (for precision)
$scaledProbability = (int)($currentProbability * 1000);
// Return true if a random number between 1 and 1000 is less than or equal to the scaled probability
return mt_rand(1, 1000) <= $scaledProbability;
}
and here some testcode:
$testDates = ['2024-01-01', '2024-06-01', '2024-12-31'];
foreach($testDates as $date) {
$trueCount = 0;
for ($i = 0; $i <=1000; $i++) {
if (randomBooleanByDate($date)) {
$trueCount++;
}
}
echo $date, ': true in ', $trueCount / 10, '%', PHP_EOL;
}
// returns something like:
// 2024-01-01: true in 8%
// 2024-06-01: true in 24.9%
// 2024-12-31: true in 49.3%