%This script simulates the Linear congruential random number generator developed by Knuth. %This random number generator generates random number uniformly distributed between 0 and 1. %The random number generator implments a recursive algorithm of the form: % % x(n) = (a*x(n-1)+c) mod (m) % x(n) = ((a+c)*x(n-1)) mod m -> our implementation % % where: a - mulitplier from 0 <= a < m % c - increment 0 <= c < m % m - modulus 0 < m % x(-1) - iniital condition - seed % %To make the random number generator uniformly distributed between -1 and +1 we take each %sample from the random number generator; scale it; subtract by the mean of the 0 to 1 random %number generator which is .5; and multiply by 2. Please note that that x(n-1) is the value %BEFORE any shifting is done or the recursive algorithm will not work. % %This simulation compares Matlabs random number generator and our developed random number %generator by displaying adjacent histograms. clear NUM_OF_POINTS = 10000;%000; NUM_OF_BITS = 15; Xn = zeros(NUM_OF_POINTS,1); Yn = zeros(NUM_OF_POINTS,1); seed = 5141; % $1415 The starting value 0 < seed < m a = 3; %The Multiplier 0 <= a < m c = 2^8; %The increment 0 <= c < m m = 2^NUM_OF_BITS; %The modulus 0 < m Xn(1) = seed; for i = 2:NUM_OF_POINTS x = (a+c)*Xn(i-1); Xn(i) = x - m*(floor(x/m)); %calculate mod(x,m) Yn(i) = 2*((Xn(i)/m) - .5); %Adjust the RNG to be distributed between -1 and +1 %Notice we place the output in Yn instead of Xn so %Knuth's algorithm can operate properly. end matlab_RNG = rand(NUM_OF_POINTS,1); subplot(2,1,1), hist(Yn),title('Histogram of my random number generator with distribution from -1 to 1'); matlab_RNG = (2*(matlab_RNG - .5)); %shift matlab's uniform RNG between -1 and +1 subplot(2,1,2), hist(matlab_RNG),title('Histogram of Matlab random number generator with distribution from -1 to 1');