The explanation has already been given by @chambelix, apparently, the operator mod (%)
does not work very well in PHP
when the negative divisor "module" (read the number without the negative sign) is greater than the positive dividend... Or vice versa, see tests:
echo (12345 % (-2147471303))."\n"; // Retorna 12345 (errado)
echo ((-2147471303) % 12345)."\n"; // Retorna -9173 (errado)
To have a better experience with very large negative values, there is a function that solves the problem:
function truemod($num, $mod) {
return ($mod + ($num % $mod)) % $mod;
}
echo truemod(12345,-2147471303)."\n"; // Retorna -2147471303 (certo)
echo truemod(-2147471303,12345); // Retorna 3172 (certo)
Honestly, I think the function you’re using is somewhat confusing.... I would do it that way:
for ($i = 0; $i < 10; $i++){
$numerador = (1103515245 * $i + 12345);
$seed = truemod($numerador,-2147471303);
echo "BSD: " . $seed . "\n";
}
echo "\n";
function truemod($num, $mod) {
return ($mod + ($num % $mod)) % $mod;
}
In that case: &$seed
the operator &
acts as a reference to the variable $seed
which was passed by the parent function...
/* I think it’s crazy to understand this function below, or see a utility, but ok... */
function bsd_rand($seed) {
return function() use (&$seed) {
//Retorne essa função, utilizando a mesma referencia de variável que gerou a variável $seed
}
}
In general, the operator & $variavel
then acts as a reference...
Useful links:
What are references?
What references do
I liked the currying
– Édipo Costa Rebouças
Could you explain why the expected result is -2147471303 and not 12345, just to better understand your line of reasoning? In other words, how did you calculate "manually"?
– Bacco