The following snippet of code is taken from a Pseudo-random number generator (written in ActionScript 3):
public function random():Number {
_currentSeed = (_currentSeed * 16807) % 2147483647);
return (_currentSeed/0x7FFFFFFF) + 0.000000000233;
}
The first line of the code is easy to understand, it's a standard linear congruential generator, with the multiplier being 16807
. The first part of the second line converts the resulting integer to a float roughly between 0
and 1
.
However, what is the purpose of that last part of the second line, + 0.000000000233
? Is it necessary in such an RNG, or does it serve a different purpose?
The bulk of the algorithm is a well-known prime modulus multiplicative linear congruential generator. All those prefix adjectives mean that it achieves maximum cycle length without the additive term that generalized LCGs have, so PMMLCGs were popular dating back to the 1950's because you did one less operation per invocation. You should never initialize _currentSeed
to zero, and the algorithm is designed to never yield a zero or negative number if properly implemented and seeded because it's based on integer arithmetic, which is precise. (Proper implementation means insuring the results aren't affected by integer overflow. A portable algorithm to do this was written in FORTRAN by Linus Schrage back in 1959, along with a simple test consisting of what the seed value ought to be after 1000 iterations.)
The magic number is slightly bigger than (1/2) / 0x7fffffff
, so it shouldn't push the return value up over 1. Since it's not being added to _currentSeed
, it plays no role in avoiding the fixed-point behavior that would happen if _currentSeed
was ever set to zero. Honestly, I can't see that it is accomplishing much of anything.