Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linear Congruential Generator in Python

Tags:

python

random

I am writing a LCG function in Python that I will use for a Monte Carlo type simulation for coin flips and generating runs. The problem I am facing is that when I generate a list of random numbers, the numbers are patterned such that odds and evens alternate. I don't know whether that is a property of the LCG function itself or a mistake in how I am generating the numbers.

Here is my code:

def seedLCG(initVal):
    global rand
    rand = initVal

def lcg():
    a = 1140671485
    c = 128201163
    m = 2**24
    global rand
    rand = (a*rand + c) % m
    return rand

seedLCG(1)

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

Values Returned:

10581448
11595891
1502322
14136437
11348076
1403015
9622582
11013417
11529808
15836891

I'm assuming I don't need to worry about overflow and size because int and long are interchanged as needed by Python.

like image 259
Siddharth Dhingra Avatar asked Oct 02 '13 15:10

Siddharth Dhingra


People also ask

What is linear congruential generator with example?

A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms.

How do you find a linear congruential generator?

All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n + 1} = a \times r_n + c \pmod m}

What is LCG Python?

LCG – generates as many random numbers as requested by user, using a Linear Congruential Generator. LCG uses the formula: X_(i+1) = (aX_i + c) mod m. :param num_iterations: int – the number of random numbers requested.


1 Answers

a*rand multiplies rand by an odd number, so the result is always odd when rand is odd, and even when rand is even. You then add in the odd number c, which changes odd to even and vice versa. The modulo has no effect on the last bit. So, every call to lcg flips rand from odd to even or from even to odd.

If you're serious about random numbers (but you don't need crypto-strength ones), consider using numpy.random.

like image 187
Fred Foo Avatar answered Oct 08 '22 02:10

Fred Foo