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:
NaN
?NaN
with digits behave differently than a "normal" NaN
?NaN
with digits besides initializing it that way?Decimal
class where NaN
can be followed by digits?Thanks!
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With