Pseudo Random Number Generation

tags: modulo-operator random

One of the simplest examples of a pseudorandom number generator(PRNG) is the linear congruential generator(LCG).

1
2
3
4
5
6
7
def next_random(previous, x, y, z)
  (previous * x + y) % z
end

p next_random(1, 4, 5, 6)
p next_random(3, 4, 5, 6)
p next_random(5, 4, 5, 6)

We can use this method to generate a sequence of pseudo random numbers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def next_random(previous, x, y, z)
  (previous * x + y) % z
end

def random(x, y, z)
  output = [1]
  
  while output.size <= z
    previous = output[output.size - 1]
    random_number = next_random(previous, x, y, z)
    output << random_number
  end
  
  return output
end

p random(40, 55, 67)

The generated output:

[1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2, 1, 28]

The sequence 1, 28, 36, 21, 24, 10, 53, 31, 22, 64, 2 repeats. The length of this sequence is called the period of PRNG. In this case, it is 11.