letsBeePolite
letsBeePolite

Reputation: 2251

Best practice for representing floating infinity in python 3.x

Since a very large floating value can be represented as follows: sys.float_info.max and float("inf").

Is one better than the other? If yes, under what circumstances?

Or which is one more preferred for scientific computing?

Upvotes: 2

Views: 260

Answers (3)

bfris
bfris

Reputation: 5805

You should consider NumPy, which is likely to come into play if you're doing scientific computing. According to docs, NumPy has

  • numpy.inf IEEE 754 Positive infinity
  • numpy.NINF IEEE 754 Negative infinity

It's odd that one is all lower case and one is all caps.

There are also several helper functions, e.g.

  • numpy.isinf which elements are + or - infinity
  • numpy.isposinf which elements are + infinity
  • numpy.isneginf which elements are - infinity
  • numpy.isfinite which elements do not belong to NaN or infinity

Unless you need crazy arbitrary high precision, NumPy could be your best choice.

Edit:

For crazy arbitrary high precision, there is also the decimal module, which provides

  • Decimal('Infinity'), Decimal('inf'), Decimal('+inf') for + infinity
  • Decimal('-Infinity'), Decimal('-inf') for + infinity

Decimal seems to not be case sensitive at all and +Infinity does not require a + sign.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308138

This should indirectly tell you everything you need to know:

>>> float('inf') > sys.float_info.max
True
>>> float('inf') <= sys.float_info.max
False

Upvotes: 2

Tim Peters
Tim Peters

Reputation: 70592

Definitely not the first:

>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

That's the largest finite float.

You're missing the preferred method ;-)

>>> import math
>>> math.inf
inf

Note also:

>>> math.nan
nan

Upvotes: 6

Related Questions