Join GitHub today
GitHub is home to over 20 million developers working together to host and review code, manage projects, and build software together.
Difference in behavior between python and numpy array add/subtract assignment operator #4704
Summary: There is a difference in how the add/subtract assignment operators work between normal Python ints and int64s in Numpy arrays that leads to potentially unexpected and inconsistent results.
Problem: Consider the following code, in which a normal Python int is typecast to a float in a new variable:
As expected, the type of y has now been cast to float, due to the addition of a float to an int.
Now, using an assignment operator on an int gives a similar result: it typecasts x as a float. I assume it needs to create new memory to cope, but it's now a float to the user.
Now consider the following operation using a numpy array, in which assignment of a new variable (y) results in typecasting the int64 to a float64, yielding the expected result.
A user may reasonably be expected to perform the add assignment operation using a numpy array with the exact same results as the parallel operation on a standard int and as shown immediately above in the numpy array, when not using an assignment operator. The following example illustrates the issue:
Expected result: A user may reasonably expect the result of this operation to be equivalent to assignment to a new variable, since this behavior is paralleled in normal Python ints. One would expect the following as a continuation from above:
Actual result: Instead of new memory being created to allocate the new dtype, numpy does this instead:
Workarounds: Obviously, the workaround is to typecast the original numpy array in the type consistent with the types with which it is expected to work (in this case, float64):
Comments: This is normally not a problem when you have overt control over the output type. But this issue was encountered in the following context, in which the user would have to explicitly re-type the resultant vector as floats instead of ints or avoid confusingly using assignment operators in this case but NOT a similar non-Numpy Python case:
It turns out that this issue affects add assignment and subtract assignment operators but not multiply (shown below) and divide assignment operators, for which it is happy to typecast the existing numpy array as a float:
System: Python 2.7.6 from MacPorts on Mac OS X 10.9.2.
This comment has been minimized.
This comment has been minimized.Show comment Hide comment
And in the future it will raise an error ;)
Python inplace isn't really inplace, for instance,