Why is there a different behavior with short assignment and NaN?

I see this in python 2.7.3, both with pylab and numpy. Why is this:

>>> x = pylab.arange(5) >>> x = x + pylab.nan >>> print x [ nan nan nan nan nan] 

different from this:

 >>> x = pylab.arange(5) >>> x += pylab.nan __main__:1: RuntimeWarning: invalid value encountered in add >>> print x [-9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808] 

?

+4
source share
1 answer

This is because arange(5) returns an array of integers, but nan is a floating point value. When you are a normal destination, this is normal, because x + nan transparently converts x to float to perform the addition and returns the result of the float. But with += it tries to return this float result to the original x , which is an int array. This fails because the int array cannot accept floating point data.

Using += with numpy arrays updates the array in place, and this will not work if the result of your calculation is different from the data type than the original.

+7
source

Source: https://habr.com/ru/post/1501198/


All Articles