% =========================================================================
%  ------  Random Number Generators (RNGs)-------------
%
% This is an m-file that examines basic Random Number Generators (RNGs)
% The following cases are considered:
%
% (a) Uniform distribution in (0,1) using the Congruential Generator
% (b) Uniform distribution in (0,1) using the Mersenne Twister algorithm
% (c) Normal distribution in (0,1) using the default algorithm in Matlab
% (a) Uniform distribution in (a,b).
%
% =========================================================================

% Clears history and command window 
close all; clear all;

% number of points (random numbers) to be created
n = 1000;
n = 100000;

% ---------- Uniform in [0,1] ----------------------
% -- Congruential Generator
%1o set parametwn
a=1229;
b=1;
y0=3;
M=2^11;
%2o set parametrwn
% a=65539;
% b=0;
% y0=1;
% M=2^31;

y=zeros(n,1);

for i=1:n
y(i)=mod(a*y0+b,M);
y0=y(i);
end
% x omoiomorfh sto [0 1]
x=y/M;

% plots
%--tyxaioi arithmoi 
figure(1)
hold on;
title('Values of X')
plot(x,'.-g')
xlabel('Iterations');
ylabel('Random numbers');
hold off;
%--istogramma pithanothta
figure(2)
hist(x,100);
title('Histogram of X')
ylabel('Frequency')
xlabel('Numbers')
%-- sysxetish
figure(3)
plot(y(1:end-2),y(2:end-1),'.b');
title('Sysxetish metaxy 2 diadoxikwn arithmwn ths Y')
xlabel('x_{2k}'); 
ylabel('x_{2k-1}'); 


% -- Mersenne Twister (defalut, "rand" function, in Matlab)
y = rand(1,n);
figure(4);
hist(y,100);
title('"n" Random Numbers: Uniform');
%-- sysxetish
figure(5)
plot(y(1:end-2),y(2:end-1),'.b');
title('Sysxetish metaxy 2 diadoxikwn arithmwn ths Y')
xlabel('x_{2k}'); 
ylabel('x_{2k-1}'); 


% ---------- Normal [0,1] ----------------------
y1 = randn(1,n);
figure(6);
hist(y1,200);
title('"n" Random Numbers: Normal');


% ---------- Uniform in [a, b] ----------------------
% The following code demonstrates a method for generating
% random numbers between (a) and (b). 
% The round function is used to round the number to the closest
% whole number.
a = 0;
b = 20;
y2 = round(a + (b-a) * rand(1,n));
figure(7);
hist(y2);
title('"n" Random Numbers: Normal between "a" and "b"');
