0

a = (random.random(), random.random())

print(a)

print(a[0])

the result is:

(0.4817527913069962, 0.7017598562799067)

0.481752791307

What extra is happening behind printing a tuple(similar behavior for list)? Why is there extra fraction?

Thanks a lot.

BTW, this is python 2.7

user7586189
  • 1,249
  • 8
  • 17
  • Duplicate of many, including this one: http://stackoverflow.com/questions/16105833/python-strangely-rounding-values/16112798#16112798 – Mark Dickinson Feb 25 '17 at 10:44

1 Answers1

4

What you are seeing is the difference between the formatting choices made by str(float) and repr(float). In Python 2.x, str(float) returns 12 digits while repr(float) returns 17 digits. In its interactive mode, Python uses str() to format the result. That accounts for the 12 digits of precision when formatting a float. But when the result is a tuple or list, the string formatting logic uses repr() to format each element.

The output of repr(float) must be able to be converted back to the original value. Using 17 digits of precision guarantees that behavior. Python 3 uses a more sophisticated algorithm that returns the shortest string that will round-trip back to the original value. Since repr(float) frequently returns a more friendly appearing result, str(float) was changed to be the same as repr(float).

casevh
  • 11,093
  • 1
  • 24
  • 35
  • BTW, Python 2.7 uses the same algorithm for float `repr` as Python 3 does. It's only Python 2.6 and earlier that construct a repr based on 17 significant digits. – Mark Dickinson Feb 25 '17 at 10:40