In python, is there hidden rules to control how to display the precision of decimal number

Viewed 66

For python, do read this link: https://docs.python.org/3/tutorial/floatingpoint.html, "Floating Point Arithmetic: Issues and Limitations"

I do understand that there is mismatch(tiny difference) between a binary-represented float & exact-decimal represented float, ex. exact-decimal represented float:: 1.005
python binary-represented float:: 1.00499999999999989341858963598497211933135986328125

here is what I typed in python:

>>> 1.005
    1.005
>>> from decimal import Decimal 
>>> Decimal(1.005)
    Decimal('1.00499999999999989341858963598497211933135986328125')

Here is my question:

  1. why python showed 1.005 when I type in 1.005? why it is not 1.00499999999999989341858963598497211933135986328125?
  2. if you tell me that python round result to some digits after decimal point, then what is rounding rule for my situation? it looks there is default rounding rule when start python, if this default rounding rule exists, how to change it?

Thanks

1 Answers

When asked to convert the float value 1.0049999999999999 to string, Python displays it with rounding:

>>> x = 1.0049999999999999; print(x)
1.005

According to the post that juanpa linked, Python uses the David Gay algorithm to decide how many digits to show when printing a float. Usually around 16 digits are shown, which makes sense, since 64-bit floats can represent 15 to 17 digits of significance.

If you want to print a float with some other number of digits shown, use an f-string or string interpolation with a precision specifier (see e.g. Input and Output - The Python Tutorial). For instance to print x with 20 digits:

>>> print(f'{x:.20}')
1.0049999999999998934
>>> print('%.20g' % x)
1.0049999999999998934
Related