Subtractive generator: Difference between revisions
Content deleted Content added
m added indentations to the seed generator algorithm. |
Restoring visibility of the task description formulae (lost in under-tested cosmetic edits at 04:25, 12 September 2016) |
||
Line 1:
{{task|Randomness}}
A ''subtractive generator'' calculates a sequence of [[random number generator|random numbers]],
The formula is
<big><big><math> r_n = r_{(n - i)} - r_{(n - j)} \pmod m </math></big></big>▼
All subtractive generators have some weaknesses.
The subtractive generator has a better reputation than the
The choice of <big><math>i</math></big> and <big><math>j</math></big> affects the period of the generator. A popular choice is <big><math>i = 55</math></big> and <big><math>j = 24</math></big>, so the formula is
▲The subtractive generator has a better reputation than the [[linear congruential generator]], perhaps because it holds more states. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of <big><big><math> r_{(n-i)} - r_{(n-j)} </math></big></big> is always between <big><big><math> -m </math></big></big> and <big><big><math> m </math></big></big>, so a program only needs to add <big><big><math> m </math></big></big> to negative numbers.
▲ <big><big><math> r_n = r_{(n - 55)} - r_{(n - 24)} \pmod m </math></big></big>
▲The subtractive generator from ''xpat2'' uses:
The implementation is by J. Bentley and comes from program_tools/universal.c of
Bentley uses this clever algorithm to seed the generator.
This generator yields the sequence
▲This generator yields the sequence <big><big><math> r_{220}</math></big></big>, <big><big><math> r_{221}</math></big></big>, <big><big><math> r_{222} </math></big></big> and so on. For example, if the seed is '''292929''', then the sequence begins with <big><big><math> r_{220} = 467478574</math></big></big>, <big><big><math> r_{221} = 512932792</math></big></big>, <big><big><math> r_{222} = 539453717</math></big></big>. By starting at <big><big><math> r_{220}</math></big></big>, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next <big><big><math> r_n</math></big></big>. Any array or list would work; a [[ring buffer]] is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from ''xpat2''.
|