Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Return max float instead of infs?

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!

like image 733
jeffalstott Avatar asked Sep 24 '11 11:09

jeffalstott


2 Answers

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
like image 108
phihag Avatar answered Sep 25 '22 14:09

phihag


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 ] )
like image 42
piwi Avatar answered Sep 21 '22 14:09

piwi