256-bit linear congruential pseudo-random number generator.
- Author
- Paul Serice
The next element in the random number sequence is returned in next
. The random numbers returned are 256 bits wide. It is possible to generate larger random numbers by calling cgul_random_lcg256__next_in_range()
which will assemble the larger numbers from multiple iterations of the generator.
The most common LCG implementation is to use a modulus that is a power of 2 allowing the modulo operation to be performed with a simple bit mask or intrinsic modulo 2 arithmetic (depending on the data type). The cgul_random_lcg256 implementation is no different; however, this results in the well-known problem that LCGs are non-random in their low-order bits. Specifically, the nth bit has a period of 2^n. Thus, the least-significant bit only has a period of 2 meaning it always just toggles between 0 and 1.
The way to get around this problem is to discard the low-order bits. This can be done by shifting to the right the value returned by this function or by using cgul_random_lcg256__next_in_range()
which returns numbers based much more heavily on the high order bits.
- Note
- Do not use the value returned by this function without compensating for the non-random low-order bits (as described above).
- Parameters
-
[in] | cex | c-style exception |
[in] | r | cgul_random_lcg256 instance |
[out] | next | next element in the random number sequence |
- See also
- cgul_random_lcg256__next_in_range()
If the value returned by cgul_random_lcg256__next()
is not the exact range that is needed, this method can limit or extend the return value to [0, range_max). If range_max
is larger than the number of bits that can be generated in one iteration, multiple iterations will be used. If the range needs to be extended beyond what can be generated in a single iteration, the Blum-Blum-Shub generator in cgul_random_bbs
is probably a better choice.
It is highly recommended that this method be used when mapping the random numbers to a smaller range because (like most LCGs), the low order bits of this LCG are known to repeat much more quickly than all the bits taken as a whole. This method takes this problem into account to return a suitable pseudo-random number.
- Parameters
-
[in] | cex | c-style exception |
[in] | r | cgul_random_lcg256 instance |
[out] | next | next element in the random number sequence |
[in] | range_max | exclusive limit on the maximum value returned |