J.doe
J.doe

Reputation: 37

How to use Linear congruential generator

I have to develop a Linear Congruential Generator with this formula Xn+1 = (aXn + b) mod m in Python. I think I understand how to generate the sequence of numbers but I don't know how to use it, for example to simulate a dice (I need a number between 1 and 6)

def seedLCG(initVal):
  global rand
  rand = initVal

def lcg():
  a = 1664525
  b = 1013904223
  m = 2**32
  global rand
  rand = (a*rand + b) % m
  return rand

seedLCG(1)

for i in range(10):
  print lcg()

Upvotes: 0

Views: 2560

Answers (1)

Sebapi
Sebapi

Reputation: 209

The LCG is a common algorithm for pseudo-random number generation. You can not use m=6 or else your LCG periodicity will be low. You need to use well chosen values of a,b and m to ensure the LCG does not have a small periodicity.

You could use a=0x19660d, b=0x3c6ef35f, m=2**32

This will produce pseudo-random integers, you can get a dice with:

dice = 1 + lcg(a,b,m) % 6

Upvotes: 1

Related Questions