o_yeah
o_yeah

Reputation: 788

How to replicate np.random result directly?

import numpy as np
np.seed(1)
a=np.random.randint(10)
b=np.random.randint(10)

I know that after setting the random seed, every time I run this code, a and b will always be initialized to some fixed value, respectively.

My question is: In a new run, how can I directly generate b's value without generating a's value first?

In my mind, I need something like:

import numpy as np
np.seed(1)
a = np.random.randint(10)
# DO SOMETHING to get some situation-specific information, something like a new seed

So that in the new run, I can do like:

# DO SOMETHING to load or set that situation-specific information
b = np.random.randint(10)

Is there any way to do this?

Upvotes: 3

Views: 287

Answers (2)

Nghi Thanh
Nghi Thanh

Reputation: 11

you can just run random function and do not need to set it for a.

first time

np.random.randint(10)
# DO SOMETHING to load or set that situation-specific information
b = np.random.randint(10)

Upvotes: 0

Chris
Chris

Reputation: 29742

IIUC, use numpy.random.get_state and set_state:

import numpy as np

a = np.random.randint(10)
a
# 5

# Now get the current state
after_a = np.random.get_state()

b = np.random.randint(10)
b
# 8

# After some work...

np.random.set_state(after_a)

b = np.random.randint(10)
b
# 8

Upvotes: 4

Related Questions