Search code examples
pythonfloating-pointprecision

Why does the Python 3 string function appear to reduce precision of float?


In a Python (3.6.7) interactive shell on Ubuntu 18, both

>>> n = str(3.140000000000000124344978758017532527446746826171875)
>>> print(n)

and

>>> print(3.140000000000000124344978758017532527446746826171875)

yield 3.14. While

>>> print('3.140000000000000124344978758017532527446746826171875')

yields 3.140000000000000124344978758017532527446746826171875

Why is this?

Note; I am not asking why floating-point numbers lose precision, but specifically, why the use of str(n) and 'n' (quotes) behave differently with print().


Solution

  • In case 1 and 2, what you manipulate is a float object

    f = 3.140000000000000124344978758017532527446746826171875
    
    # In case 1
    print(str(f))
    
    # In case 2
    print(f)
    

    And str(f) converts the float object to a string, print(f) means print(repr(f)), repr(f) also converts the float object to a string.

    In case 3, what you manipulate is a string object which contains 53 characters,

    What happened when convert a float object to a string?

    str(f) and repr(f) call the same function float_repr.

    In function float_repr, if you haven't specify precision parameter, a float object will be convert to string with double-precision floating-point format.

    Double-precision floating-point format gives from 15 to 17 significant decimal digits precision.

    So in this case, significant decimal digits precision is 16, 3.140000000000000124344978758017532527446746826171875 will be converted to 3.140000000000000.

    An clearer example:

    >>> str(3.140000000000000123)
    '3.14'
    
    >>> str(3.14000000000000123)
    '3.140000000000001'
    
    >>> print(3.14000000000000123)
    3.140000000000001