How to get a floating point infinity that when multiplied by zero gives zero
You might use the largest finite number that float
can hold:
In [9]: print sys.float_info.max
1.79769313486e+308
In [10]: sys.float_info.max * 0
Out[10]: 0.0
Rather than looking for a "smaller infinity", which doesn't exist, it may be easier to trap the NaN
and substitute zero for it. To do this, you can use the fact that NaN
is not equal to any float value, even itself. This approach is convenient because generally you can use it at the end of a chain of calculations (since the NaN
will cascade through and make the results all NaN
).
possible_inf = float("+inf")
result = possible_inf * 0
result = result if result == result else 0
You could also just trap for the infinity itself earlier on:
possible_inf = float("+inf")
result = 0 if abs(possible_inf) == float("+inf") else possible_inf * 0
NAN isn't zero. u can use numpy to check the NAN value and convert it to zero.
from numpy import isnan
result = 0 if isnan(result) else result