3

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

steve
  • 41
  • 2
  • 1
    "why python showed 1.005 when I type in 1.005? " because `float.__str__` tries to show you something "pretty", that is accurate yet minimal. Not the closest decimal representation possible. Various languages and language implementations have different rules about how to format floats. It is very important to understand, *you can't round a float to 1.5* because *that number is not representable in binary floating point. – juanpa.arrivillaga Feb 02 '21 at 07:59
  • So, this is relevant, although the question isn't exactly a duplicate, it has a lot of good information: https://stackoverflow.com/questions/55727214/inconsistent-printing-of-floats-why-does-it-work-sometimes#:~:text=Python%20now%20uses%20David%20Gay's,doesn't%20change%20its%20value. – juanpa.arrivillaga Feb 02 '21 at 08:04
  • Another good question: https://stackoverflow.com/questions/7153979/algorithm-to-convert-an-ieee-754-double-to-a-string – juanpa.arrivillaga Feb 02 '21 at 08:06
  • So note, the algorithm tries to find the shortest representation that *doesn't* change the value. – juanpa.arrivillaga Feb 02 '21 at 08:08

1 Answers1

0

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
Pascal Getreuer
  • 2,906
  • 1
  • 5
  • 14