Andrew Clark
Andrew Clark

Reputation: 208465

Meaning of digits after NaN in Python Decimal object

I was reading the lexical definition for valid decimal string syntax in the documentation for decimal.Decimal and the following struck me as kind of odd:

nan            ::=  'NaN' [digits] | 'sNaN' [digits]

This looked really strange to me, but apparently digits can be included after 'NaN' without any issues, but any character besides digits after 'NaN' raises InvalidOperation.

>>> Decimal('NaN10')
Decimal('NaN10')

So I have a few questions about this:

  1. What is the meaning of digits that are a part of NaN?
  2. How do instances of NaN with digits behave differently than a "normal" NaN?
  3. Are there ways to obtain a NaN with digits besides initializing it that way?
  4. Are there other places in Python besides the Decimal class where NaN can be followed by digits?

Thanks!

Upvotes: 9

Views: 457

Answers (1)

kennytm
kennytm

Reputation: 523264

It is an IEEE-754 feature to distinguish between different kinds of NaNs (the "payload"). The digits are encoded into the mantissa of the number:

>>> Decimal("NaN456").as_tuple()
DecimalTuple(sign=0, digits=(4, 5, 6), exponent='n')
>>> Decimal("NaN123").as_tuple()
DecimalTuple(sign=0, digits=(1, 2, 3), exponent='n')
>>> Decimal("NaN").as_tuple()
DecimalTuple(sign=0, digits=(), exponent='n')

The sole purpose of the payload is for diagnosis. These NaNs are no different from "normal" NaNs.

Upvotes: 6

Related Questions