I have several functions with multiple calculations that might return inf
, like so:
In [10]: numpy.exp(5000)
Out[10]: inf
I'd rather it return the maximum float value:
In [11]: sys.float_info.max
Out[11]: 1.7976931348623157e+308
I could put in checks for every time an inf
might pop up, or wrap each calculation in a function that rounds inf
down to the desired float. However, I'd really like a simple hack at the beginning of every function, like:
inf = sys.float_info.max
Which obviously doesn't work. Is there a smart way to do this? Thanks!
You can use a decorator:
import sys
def noInf(f):
def wrapped(*args, **kwargs):
res = f(*args, **kwargs)
if res == float('inf'):
return sys.float_info.max
return res
return wrapped
@noInf
def myMult(x, y):
return x*y
print(myMult(sys.float_info.max, 2)) # prints 1.79769313486e+308
I don't know about 'replacing' infinity value, but what about using min()
?
Something like (assuming x
yields your value):
return min ( [ x, sys.float_info.max ] )
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