Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of digits after NaN in Python Decimal object

Tags:

python

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!

like image 893
Andrew Clark Avatar asked Apr 22 '11 16:04

Andrew Clark


People also ask

How do you print 6 digits after a decimal in Python?

Use the round() function to print a float to 6 decimal places, e.g. print(round(my_float, 6)) . The round() function will round the floating-point number to 6 decimal places and will return the result.

What is a number with a decimal point called in Python?

Floats are decimals, positive, negative and zero. Floats can also be numbers in scientific notation which contain exponents. In Python, a float can be defined using a decimal point .

What is decimal () in Python?

In Python, there is a module called Decimal, which is used to do some decimal floating point related tasks. This module provides correctly-rounded floating point arithmetic. To use it at first we need to import it the Decimal standard library module. import decimal.


1 Answers

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.

like image 142
kennytm Avatar answered Oct 07 '22 14:10

kennytm