Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there different behavior with short-hand assignment and NaN?

Tags:

python

numpy

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]

?

like image 624
chappy Avatar asked Mar 22 '23 12:03

chappy


1 Answers

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.

like image 171
BrenBarn Avatar answered Apr 06 '23 19:04

BrenBarn