Sir Cost
Sir Cost

Reputation: 85

Random numbers algorithm

I need to generate random numbers in groups: 100, 500, 1000 and 10000 numbers uniforms and gaussians. This is necessary for create some histograms and other statistic stuff.

The condition is not to use python's native random function, so I was thinking to use this method (linear congruential generator): Xn+1 ≡ (aXn + c) mod m. Here I need 4 variables. Can someone please tell me how can i implement this algorithm? I assume that the m variable the first time is 100

Upvotes: 0

Views: 4119

Answers (1)

Salvador Dali
Salvador Dali

Reputation: 222929

You already know that this is Linear congruential generator, so what is so hard to read it up?

It tells you the formula you already know enter image description here and an explanation how you should select them:

The period of a general LCG is at most m, and for some choices of factor a much less than that. Provided that the offset c is nonzero, the LCG will have a full period for all seed values if and only if:

1) c and m are relatively prime

2) a - 1 is divisible by all prime factors of m

3) a - 1 is a multiple of 4 if m is a multiple of 4.

They even give you some examples of these values in the table below. This is more than enough to implement a simple function:

def LCG(seed, n, a=1664525, c=1013904223, m=2**32):
    numbers = []
    for i in xrange(n):
        seed = (a * seed + c) % m
        numbers.append(seed)

    return numbers

print LCG(3, 5)

Upvotes: 3

Related Questions