1

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().

phuclv
  • 37,963
  • 15
  • 156
  • 475
Jack
  • 10,313
  • 15
  • 75
  • 118
  • 2
    Very few people want to see `3.140000000000000124344978758017532527446746826171875` when they `print(3.14)`. – user2357112 Dec 12 '18 at 19:33
  • 1
    The first two are converting a number to a string, but the third doesn't involve any conversion and is just printing a string as-is – charley Dec 12 '18 at 19:33
  • https://github.com/python/cpython/blob/master/Objects/floatobject.c – Andrew Li Dec 12 '18 at 19:34
  • Relevant: https://stackoverflow.com/questions/24187684/python-change-repr-floating-digits – roganjosh Dec 12 '18 at 19:37
  • 1
    "why the use of str(n) and 'n' (quotes) behave differently" - they're not supposed to behave the same. `str` is not supposed to be equivalent to putting quotation marks around an expression. For a super-simple example, look at what you literally wrote - you wouldn't expect `str(n)` to be `'n'` unless you had assigned `n='n'`, would you? – user2357112 Dec 12 '18 at 19:42
  • `int` objects and `str` objects are different, why would you expect their `__str__` methods to be the same? – juanpa.arrivillaga Dec 12 '18 at 19:44

1 Answers1

3

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
Char
  • 778
  • 5
  • 10