waitingkuo
waitingkuo

Reputation: 93754

Something strange in numpy

a is a numpy array and a.T is it's transpose. Once I add a and a.T as a += a.T, the answer isn't expected. Could any one tell me why? Thanks.

import numpy 

a = numpy.ones((100, 100))
a += a.T
a

array([[ 2.,  2.,  2., ...,  2.,  2.,  2.],
       [ 2.,  2.,  2., ...,  2.,  2.,  2.],
       [ 2.,  2.,  2., ...,  2.,  2.,  2.],
       ..., 
       [ 3.,  3.,  3., ...,  2.,  2.,  2.],
       [ 3.,  3.,  3., ...,  2.,  2.,  2.],
       [ 3.,  3.,  3., ...,  2.,  2.,  2.]])

Upvotes: 2

Views: 163

Answers (1)

seberg
seberg

Reputation: 8975

Note that a.T is only a view on a, which means they hold the same data. Now:

 a += a.T

Adds a.T in place to a, but while doing so, changes a.T (as a.T points at the same data). Since the order of accessing a is a bit more complex, this fails (and you should not trust the result to be reproducable, because it will change when you change np.setbufsize.

To avoid it both of these will work, though the first version seems cleaner to me.

a = a + a.T
a += a.T.copy()

Upvotes: 8

Related Questions