So Python has positive and negative infinity:
float("inf"), float("-inf")
This just seems like the type of feature that has to have some caveat. Is there anything I should be aware of?
So Python has positive and negative infinity:
float("inf"), float("-inf")
This just seems like the type of feature that has to have some caveat. Is there anything I should be aware of?
So does C99.
The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac≠0).
All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.
You can still get not-a-number (NaN) values from simple arithmetic involving inf:
>>> 0 * float("inf")
nan
Note that you will normally not get an inf value through usual arithmetic calculations:
>>> 2.0**2
4.0
>>> _**2
16.0
>>> _**2
256.0
>>> _**2
65536.0
>>> _**2
4294967296.0
>>> _**2
1.8446744073709552e+19
>>> _**2
3.4028236692093846e+38
>>> _**2
1.157920892373162e+77
>>> _**2
1.3407807929942597e+154
>>> _**2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: (34, 'Numerical result out of range')
The inf value is considered a very special value with unusual semantics, so it's better to know about an OverflowError straight away through an exception, rather than having an inf value silently injected into your calculations.
Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance. Recently, a fix has been applied that allows "infinity" as well as "inf", but that's minor glitch.
What you should be aware of: any number is higher then -inf and any number is lower then +inf. When compared for equality, +inf and +inf are equal, as are -inf and -inf. This may be controversial, but it's the standard.
Any calculation with infinity yields infinity, except when the result would be undefined (as with multiplied by zero, see other example in this thread), which will yield NaN.
EDIT: expanded.
There were a ton of caveats, but luckily, PEP 754 was implemented for Python 2.6, to make the float behavior more consistent across Python's platforms.
PEP 754 (Rejected):
Several ideas of this PEP were implemented for Python 2.6. float('inf') and repr(float('inf')) are now guaranteed to work on every supported platform with IEEE 754 semantics.