I see this in python 2.7.3, with both pylab and numpy. Why is this:
>>> x = pylab.arange(5)
>>> x = x + pylab.nan
>>> print x
[ nan nan nan nan nan]
different than this:
>>> x = pylab.arange(5)
>>> x += pylab.nan
__main__:1: RuntimeWarning: invalid value encountered in add
>>> print x
[-9223372036854775808 -9223372036854775808 -9223372036854775808
-9223372036854775808 -9223372036854775808]
?
It's because arange(5)
returns an array of integers, but nan
is a float value. When you ise regular assignment, this is okay, because x + nan
transparently converts x
to float to do the addition and returns a float result. But with +=
, it tries to put this float result back into the original x
, which is an int array. This fails, because the int array can't accept float data.
Using +=
with numpy arrays updates the array in place, and this won't work if the result of your computation is of a different datatype than the original.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With