jeudi 1 juin 2023

Python Local random seed

I have a random seed set at the start of my run for reproducability. But there are a few sub-functions (e.g. rando) that also use random numbers. If i used a different random number seed just for those, it affects the random seed outside of the function. Is it possible to set the random seed and use it only locally inside the function and the random state outside the function does not get affected? I believe i can always get the random state, save it and retore it. Would there be an easier option? I showed an example below.

def rando():
    np.random.seed(420)
    np.random.randint(1, 100)
    np.random.randint(1, 100)
    return None


np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
for n in range(3):
    np.random.randint(1,100) # outputs : 91,56,21

Is it possible to make the function below also output the same thing?

np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
rando()
for n in range(3):
    np.random.randint(1,100) # would like it to output : 91,56,21



Aucun commentaire:

Enregistrer un commentaire