How do I get a "small enough" infinity that its product with zero is zero?
I'm using an integer programming solver for Python, and some of my variables have infinite cost. I can't use float('inf')
because float('inf')*0 = NaN
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
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