float("nan") in set or as key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 4 05:35:39 EDT 2011


On Fri, 03 Jun 2011 23:04:38 -0700, Ethan Furman wrote:

> Steven D'Aprano wrote:
>> NANs are not necessarily errors, they're hardly silent, and if you
>> don't want NANs, the standard mandates that there be a way to turn them
>> off.
> 
> So how does one turn them off in standard Python?

Turn them off? You have to find a way to turn them on first! What makes 
you think that Python supports IEEE-754 for floats?

By default, Decimal raises exceptions for division by zero.

>>> import decimal
>>> 1/decimal.Decimal(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.1/decimal.py", line 1359, in __rtruediv__
    return other.__truediv__(self, context=context)
  File "/usr/local/lib/python3.1/decimal.py", line 1292, in __truediv__
    return context._raise_error(DivisionByZero, 'x / 0', sign)
  File "/usr/local/lib/python3.1/decimal.py", line 3812, in _raise_error
    raise error(explanation)
decimal.DivisionByZero: x / 0 


To get INF or NAN semantics is easy for decimal:

>>> decimal.setcontext(decimal.ExtendedContext)
>>> 1/decimal.Decimal(0)
Decimal('Infinity')


but impossible for float. The best you can do is subclass float, or 
surround each calculation in a try...except, which defeats the point of 
them.

In general, Python goes to great trouble and expense to avoid generating 
any float INFs or NANs -- and when it does generate them, it's normally 
at the whim of the C maths library and therefore non-portable.

>>> math.sqrt(-1.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

>>> decimal.Decimal(-1).sqrt()
Decimal('NaN')


And sometimes inconsistently so:

>>> math.fsum([1, 2, float('inf'), float('nan')])
nan
>>> math.fsum([1, 2, float('inf'), float('-inf')])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: -inf + inf in fsum



-- 
Steven



More information about the Python-list mailing list