Main Page EEng School DCU

Section 7: Random Number Generators (Matlab Examples).

    ·    Monte Carlo Methods
    ·    Random Numbers
    ·    Random Number Cycle
    ·    Linear Congruential Generators
    ·    Multiplicative LCG
    ·    Mixed LCG

lcg.m this  Matlab code implements a comprehensive function  LCG(a, c, m, X0) with the following inputs and outputs:

  • inputs:
  • outputs:
  • Below is given the Matlab code for the function. Stedents can generate random numbers using different input parameters.

    function [p, mean, var, oneperiod]=lcg(a, c, m, x)
    % Linear Congruential Generators
    % x the initial seed, 0 <= c < m
    % a the multiplier, 0 <= a < m, normally greater than 1
    % c the increment 0 <= c < m
    % m the modulus, prime numbers are best
    for j=1:m+5  % generate m+5 integers
      x= rem((a*x+c),m);   % (a*x + c) mod m;
      xseq=[xseq;x];  % concatenate numbers, in a cloumn
      row=xseq';  % transpose to a row

    % find out the period
    while row(i) ~= row(j)
      if j > m  % integer row(i) doesn’t repeat in the sequence
        i=i+1;  % see if the next integer repeats or not
    % one period of random integer number
    oneperiod=row(i:i+p+2);   % one period and three integers

    % calculate the real number of a period p
     r=row(i:i+p-1)/m;  % divide by m, so distributed in [0,1)
     mean = sum(r)/p; % average
     var=sum(square)/p; % variance

    However, Matlab environment has already predefined functions to generate random numbers:

    RAND   Uniformly distributed random numbers.

    RANDN  Normally distributed random numbers.

    SPRAND Sparse uniformly distributed random matrix.

    SPRANDN Sparse normally distributed random matrix.

    RANDPERM Random permutation.

    Valentin Muresan, Dublin City University,