arrays - Difference between a -= b and a = a - b in Python -
i have applied this solution averaging every n rows of matrix. although solution works in general had problems when applied 7x1 array. have noticed problem when using -= operator. make small example:
import numpy np = np.array([1,2,3]) b = np.copy(a) a[1:] -= a[:-1] b[1:] = b[1:] - b[:-1] print print b which outputs:
[1 1 2] [1 1 1] so, in case of array a -= b produces different result a = - b. thought until these 2 ways same. difference?
how come method mentioning summing every n rows in matrix working e.g. 7x4 matrix not 7x1 array?
note: using in-place operations on numpy arrays share memory in no longer problem in version 1.13.0 onward (see details here). 2 operation produce same result. answer applies earlier versions of numpy.
mutating arrays while they're being used in computations can lead unexpected results!
in example in question, subtraction -= modifies second element of a , uses modified second element in operation on third element of a.
here happens a[1:] -= a[:-1] step step:
aarray data[1, 2, 3].we have 2 views onto data:
a[1:][2, 3], ,a[:-1][1, 2].the in-place subtraction
-=begins. first element ofa[:-1], 1, subtracted first element ofa[1:]. has modifieda[1, 1, 3]. havea[1:]view of data[1, 3], ,a[:-1]view of data[1, 1](the second element of arrayahas been changed).a[:-1][1, 1], numpy must subtract second element which 1 (not 2 anymore!) second element ofa[1:]. makesa[1:]view of values[1, 2].aarray values[1, 1, 2].
b[1:] = b[1:] - b[:-1] not have problem because b[1:] - b[:-1] creates new array first , assigns values in array b[1:]. not modify b during subtraction, views b[1:] , b[:-1] not change.
the general advice avoid modifying 1 view inplace if overlap. includes operators -=, *=, etc. , using out parameter in universal functions (like np.subtract , np.multiply) write 1 of arrays.
Comments
Post a Comment