float("nan") in set or as key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jun 5 21:21:43 EDT 2011


On Mon, 06 Jun 2011 09:13:25 +1000, Chris Angelico wrote:

> On Mon, Jun 6, 2011 at 8:54 AM, Chris Torek <nospam at torek.net> wrote:
>> A signalling NaN traps at (more or less -- details vary depending on
>> FPU architecture) load time.
> 
> Load. By this you mean the operation of taking a bit-pattern in RAM and
> putting it into a register? So, you can calculate 0/0, get a signalling
> NaN, and then save that into a memory variable, all without it trapping;
> and then it traps when you next perform an operation on that number?

The intended behaviour is operations on "quiet NANs" should return NANs, 
but operations on "signalling NANs" should cause a trap, which can either 
be ignored, and converted into a quiet NAN, or treated as an exception.

E.g. in Decimal:


>>> import decimal
>>> qnan = decimal.Decimal('nan')  # quiet NAN
>>> snan = decimal.Decimal('snan')  # signalling NAN
>>> 1 + qnan
Decimal('NaN')
>>> 1 + snan
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.1/decimal.py", line 1108, in __add__
    ans = self._check_nans(other, context)
  File "/usr/local/lib/python3.1/decimal.py", line 746, in _check_nans
    self)
  File "/usr/local/lib/python3.1/decimal.py", line 3812, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: sNaN



> Apologies, this is getting quite off-topic and away from Python.

Not at all. I think this is a big myth, that the IEEE-754 standard is 
irrelevant for high-level programming languages. It's not.

The state of the art of floating point is in a poor state. Not anywhere 
near as poor as the bad old days before there was *any* standardization 
at all, things were terrible back then, but ignoring the hard-earned 
lessons of those who lived through the days before the standard is a 
mistake. IEEE-754 is not just for hardware, particularly since now the 
vast majority of machines run hardware which almost completely conforms 
to IEEE-754. The bottleneck now is not hardware, but languages that don't 
treat floating point maths correctly.

http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf


(The article is seven years old now, but as far as I know, the criticisms 
still apply.)


-- 
Steven



More information about the Python-list mailing list