Search code examples
pythonnumpyrandom

Subtracting 1 from a numpy array gives two different answers


Why are outputs in the two cases different. I am new to this library

Case 1

import numpy as np


np.random.seed(2)

array = np.random.random((3,1))
print('Printing array : \n', array)
print('printing array - 1 : \n',array-1)
Output :
Printing array : 
[[0.4359949 ]
[0.02592623]
[0.54966248]]
printing array - 1 : 
[[-0.5640051 ]
[-0.97407377]
[-0.45033752]]

This is ok as 1 is subtracted from each element

Case 2

print('Printing array : \n', np.random.random ((3,1))-1)

Output:

Printing array : 
 [[-0.56467761]
 [-0.5796322 ]
 [-0.66966518]]

Whay are the two outputs different? np.random.random ((3,1)) should be same in both cases ( same seed) and so subtracting 1 should produce the same output. what am I messing up?

I ran the code as was expecting the same output in both cases


Solution

  • The reason why you got different arrays has been explained elaborately by @Jon Skeet.


    One workaround is to customize a function by packing the random seed together with the random number generator function, e.g.,

    def runif(shape, seed = 2): 
      np.random.seed(seed)
      return np.random.random(shape)
    
    for iter in range(2):
      print(f'Print array{iter}: \n {runif((3,1))-iter} \n')
    

    and you will see

    Print array0: 
     [[0.4359949 ]
     [0.02592623]
     [0.54966248]] 
    
    Print array1: 
     [[-0.5640051 ]
     [-0.97407377]
     [-0.45033752]]