Zihao Wang
Zihao Wang

Reputation: 57

Randomness of np.random.shuffle

I have two arrays (i and j) that are exactly the same. I shuffle them with a specified random seed.

import numpy as np
np.random.seed(42)

i = np.array([0, 1, 2, 3, 4, 5, 6, 7])
j = np.array([0, 1, 2, 3, 4, 5, 6, 7])
np.random.shuffle(i)
np.random.shuffle(j)
print(i, j)

# [1 5 0 7 2 4 3 6] [3 7 0 4 5 2 1 6]

They were supposed to be the same after shuffling, but it is not the case.

Do you have any ideas about how to get the same results (like the example below) after shuffling?

# [1 5 0 7 2 4 3 6] [1 5 0 7 2 4 3 6]

Many thanks in advance!

Upvotes: 1

Views: 487

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114791

Calling seed() sets the state of a global random number generator. Each call of shuffle continues with the same global random number generator, so the results are different, as they should be. If you want them to be the same, reset the seed before each call of shuffle.

Upvotes: 3

Related Questions