apitsch
apitsch

Reputation: 1702

Make numpy.random generated numbers consistent across different functions

Assume you have two functions like these:

import numpy as np


def function_1(seed):

    res = []
    np.random.seed(seed)
    for i in range(10):
        res.append(np.random.rand())

    return res


def function_2(seed):

    res = []
    np.random.seed(seed)
    for i in range(10):
        a = np.random.rand()  # necessary!
        res.append(np.random.rand())

    return res

They are basically the same, just that in function_2 you are required to generate an additional random number for each run of the for-loop.

Now,

x = function_1(1)
y = function_2(1)
x == y
>>> False

However, you need to make sure that the returned res is identical for both functions. Is there a better way than changing function_1 to the following?

def function_3(seed):

    res = []
    np.random.seed(seed)
    for i in range(10):
        np.random.rand()
        res.append(np.random.rand())

    return res

Then,

z = function_3(1)
y == z
>>> True

Upvotes: 0

Views: 69

Answers (1)

John Zwinck
John Zwinck

Reputation: 249303

Use a dedicated RandomState for the sequence that must be identical:

def function_2(seed):

    res = []
    random1 = np.random.RandomState(seed)
    for i in range(10):
        a = np.random.rand() # uses global state, no explicit seed
        res.append(random1.rand())

    return res

By the way, you really should try res = random1.rand(10) to do it without the loop. It will be faster.

Upvotes: 2

Related Questions