0

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

5
  • I doubt you will find a good linear congruential generator with m=100. You should look at generators with much larger m. Even better, implement Mersenne Twister if you have time. Then use other techniques to get the final result into the uniform range you want or to convert the output of your generator to gaussians (there have been various previous questions here on similar topics, so look them up). Commented Aug 5, 2015 at 5:39
  • i have tried this: n=1 c=3 x=0 m=100 for i in range(100): x = (a*x+c) % m Commented Aug 5, 2015 at 5:41
  • thank you so much david, i will check out Commented Aug 5, 2015 at 5:44
  • @DavidK python's native PRNG is Mersenne Twister. Commented Aug 5, 2015 at 12:54
  • @pjs Glad to learn that. It might be relevant to know why the condition not to use the native function was imposed. If it was "I want you to have the experience of implementing a random number generator rather than just calling random.randint()" then any good RNG should be fair game to implement. If it was "I want to you implement an RNG that isn't Mersenne Twister so we can compare the two algorithms" then of course one cannot use MT. Commented Aug 5, 2015 at 13:09

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much salvador, I really really apreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.