DEV Community

Discussion on: How do you do random?

Collapse
 
thebadgateway profile image
Will F

Python has a few options, including the numpy module. Regardless of language, however, it often only takes a ~20 lines to define a pseudo-random (in numerical math we avoid saying "random") number generator method. Here is an implementation of the so-called Mersenne twister:

def rando(n, seed, S = [0, 10, 'integer']):
    i = int(16807)
    j = int(2147483647)
    u_list = []
    if S[2] == 'real':
        for k in range(n):
            seed = (i * seed) % j
            u = (S[1] - S[0]) * (float(seed) / float(j)) + S[0]
            u_list.append(u)
        return u_list
    elif S[2] == 'integer':
        for k in range(n):
            seed = (i * seed) % j
            u = int((S[1] - S[0] + 1) * (float(seed) / float(j)) + S[0])
            u_list.append(u)
        return u_list
    else:
        print('Set of numbers to draw from is undefined')

In this method, we declare two integers, i (16807 = 75), and j (the Mersenne prime). In specifying the arguments n (number of psuedo-random numbers desired), seed (for repeatability of the pseudo-random numbers), and S (min, max, types to be generated), what is repeatedly happening (depending on n) is that we are taking the remainder of (seed * i) and j, and dividing by j; over and over. This implementation of the Mersenne Twister is good for about 230 random numbers before it repeats itself. :)