[Numpy-discussion] Shared memory check on in-place modification.

Sturla Molden sturla.molden at gmail.com
Mon Jul 27 16:51:52 EDT 2015


On 27/07/15 22:10, Anton Akhmerov wrote:
> Hi everyone,
>
> I have encountered an initially rather confusing problem in a piece of
> code that attempted to symmetrize a matrix: `h += h.T`
> The problem of course appears due to `h.T` being a view of `h`, and
> some elements being overwritten during the __iadd__ call.

Here is another example

 >>> a = np.ones(10)
 >>> a[1:] += a[:-1]
 >>> a
array([ 1.,  2.,  3.,  2.,  3.,  2.,  3.,  2.,  3.,  2.])

I am not sure I totally dislike this behavior. If it could be made 
constent it could be used to vectorize recursive algorithms. In the case 
above I would prefer the output to be:

array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,  10.])

It does not happen because we do not enforce that the result of one 
operation is stored before the next two operands are read. The only way 
to speed up recursive equations today is to use compiled code.


Sturla





More information about the NumPy-Discussion mailing list