Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy producing different random numbers despite seed [closed]

Tags:

python

numpy

I had a problem with NumPy producing different random numbers despite seeding.

code:

import numpy as np
import random

random.seed(1234)

vec = np.random.normal(0, 1, size=6)

print(vec)

As I had set the seed, I expected vec to contain the same random numbers in every run.

But what I got:

  1. run: vec = [-0.80715758 0.8377004 -0.98711439 -0.23424405 -1.85368722 0.97827818]
  2. run: vec = [-0.74409802 -0.85180205 0.84585489 -0.40506222 -1.31125093 -1.23055255]
  3. run: vec = [ 2.21521007 1.38577035 0.25437804 0.84529466 -0.83334042 1.00452671]

I was just posting this question when I found the solution.
But to prevent others from doing the same mistake, I thought it might be a good idea to post it anyway.

like image 904
JavAlex Avatar asked Mar 27 '26 06:03

JavAlex


1 Answers

My mistake was the following:
I set the seed of random, not of np.random!

When setting the seed of the NumPy random number generator, everything works as expected:

import numpy as np

np.random.seed(1234)

vec = np.random.normal(0, 1, size=6)

vec will always contain the same random numbers.

like image 105
JavAlex Avatar answered Mar 29 '26 18:03

JavAlex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!