0

I am trying to learn how ndarrays work after seeing how the plus equals operator (+=) is used in this tutorial. My code is the following:

cov = np.random.uniform(.2, .4, (2, 2))
display('cov', cov)
oldcov = cov
covT = cov.T
cov += covT
cov2 = oldcov + covT
display('cov.T', covT)
display('cov += cov.T', cov)
display('cov = cov + cov.T', cov2)
display('cov - cov - cov.T', cov - oldcov - covT)
display('cov - cov - cov.T', cov2 - oldcov - covT)

And the output the following, with my observations edited in:

'cov'
array([[0.32258373, 0.33701686],
       [0.36291378, 0.24004231]])
'cov.T, Wrong because was expecting exact same values as cov, but transposed'
array([[0.64516745, 0.69993064],
       [0.69993064, 0.48008463]])
'cov += cov.T, Wrong because 0.322 + 0.645 != 0.645. Instead of += operator, the equals (=) operator was applied'
array([[0.64516745, 0.69993064],
       [0.69993064, 0.48008463]])
'cov = cov + cov.T, Weird because different result as += operator, but it's not a correct addition. '
array([[1.2903349 , 1.39986128],
       [1.39986128, 0.96016926]])
'cov - cov - cov.T, subtracting from cov that had += applied.'
array([[-0.64516745, -0.69993064],
       [-0.69993064, -0.48008463]])
'cov - cov - cov.T, substracting from cov that didn't have += operator applied shows expected behavior.'
array([[0., 0.],
       [0., 0.]])

These behaviors don't make sense to me. How do I take the transpose of an array and add them together if I so chose?

  • When it comes to numpy arrays, saying `oldcov = cov`, the data isn't copied, just the pointer. What that means is that `oldcov` and `cov` both look at the same place in memory (you can check this by printing out `id(oldcov)` and `id(cov)` after setting them equal. So, if you change the value in `cov`, you'll also be changing the value of `oldcov`. I recommend using the `id` command after each operation and looking at what each variable actually is. – jared Jun 12 '23 at 17:00
  • Also see: https://stackoverflow.com/questions/3059395/numpy-array-assignment-problem – jared Jun 12 '23 at 17:02

0 Answers0