function count_decimals($x){
return strlen(substr(strrchr($x+"", "."), 1));
}
function random($min, $max){
echo "Min $minn";//return as Min 4.008E-7
echo "Max $maxn";//return as Max 4.02E-7
die();
$decimals = max(count_decimals($min), count_decimals($max));
$factor = pow(10, $decimals);
return rand($min*$factor, $max*$factor) / $factor;
}
$answer = random(0.0000004008, 0.000000402);
echo "n" . $answer . "n";
The value send in for $min and $max is send in as scientific notation, thus the result return as invalid decimal place, when I did an echo for the result.
How do I fix such that the function able to return the random decimal between the 2 min, max, expected response should be
between
0.0000004009 to 0.0000004019 (smaller than 0.000000402, and bigger than 0.0000004008)
2
Answers
First of all, when you need to run with big number or high precision, you should BCMath functions.
But BCMath doesn’t have random functions.
What you can use is multiply your number by 10^n to reach something than can be safely use with
random_int
for example ?If you are using PHP 8.3 or later, there is a function built in for this purpose: RandomRandomizer::getFloat.
As you can see by the detail on that manual page, the algorithm for making sure you have an evenly distributed chance is complicated by the way floating point values work: you have to avoid picking values that will be rounded to fit in the representation.
You could attempt to implement the algorithm yourself based on the C code, which I believe is here: https://github.com/php/php-src/blob/master/ext/random/gammasection.c
With the built-in function, though, you can simply do this: