80 likes | 248 Views
Random Numbers. Dick Steflik. Pseudo Random Numbers. In most cases we do not want truly random numbers most applications need the idea of repeatability to be able to debug
E N D
Random Numbers Dick Steflik
Pseudo Random Numbers • In most cases we do not want truly random numbers • most applications need the idea of repeatability to be able to debug • if we used truly random numbers how would we be able to debug a program, every time we would run the program it would be a different problem • What we really want is something that will appear to be random but will be able to reproduce a sequence
Generation Uniform Random Numbers • Consider a methos for generating a sequence of random fractions (Random real numbers ) Un • uniformly distributed between 0 and 1 • Since a computer can only represent a real number with finite accuracy we’ll actually generate integers Xn between 0 and some number m • The fraction Un = Xn / m • will always be between 0 and 1 • Usually m is the word size of the computer so that Xn can be regarded as the integer content of of a computer word with the radix point assumed at the far-right. • Un can be regarded as the contents of the same word with the radix point at the far-left.
The Linear Congruential Method By far the most popular random number generators in use today are special cases of the following scheme, introduced by D.H.Lehmer in 1949. Choose 4 “magic numbers: m, the modulus; m > 0 a, the multiplier; 0 <= a < m c, the increment; 0 <= c < m X0 the Starting value; 0 <= Xo < m The desired sequence is then: Xn+1 = (aXn + c) mod m, n >= 0 This is called a linear congruential sequence
Example For m = 10 ; X0 = a = c = 7 the sequence is 7, 6, 9, 0, 7, 6, 9, 0 notice: that the sequence has a period of 4; I.e. it repeats and will do so forever. This will happen for any linear congruential generator.
Sample #include <iostream.h>int seed; int random() { int num = (13*seed+11) % 11; seed = num; return num; } int main() { cout << "input a seed number = "; cin >> seed; cout << "\n"; for int j = 0 ; j < 20 ; j++) cout << random() << " "; }