Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a floating point infinity that when multiplied by zero gives zero

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

like image 808
wlad Avatar asked Mar 15 '16 15:03

wlad


3 Answers

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
like image 142
Robᵩ Avatar answered Sep 27 '22 19:09

Robᵩ


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 
like image 37
kindall Avatar answered Sep 27 '22 19:09

kindall


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
like image 42
qvpham Avatar answered Sep 27 '22 18:09

qvpham