samedi 6 octobre 2018

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




Aucun commentaire:

Enregistrer un commentaire