5

If i run following on python2.7 console it giving me output as:

>>> 1.2 - 1.0
0.19999999999999996

>>> print 1.2 - 1.0 
0.2

While i am running same operation in python3.5.2

>>> 1.2 - 1.0
0.19999999999999996

>>> print(1.2 - 1.0)
0.19999999999999996

I want to know why in python2.7.12 print statement giving me only 0.2 but in python3.5.2 print function giving me 0.19999999999999996.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Prem Narain
  • 91
  • 1
  • 11
  • 2
    It's the same number internally, but they changed the display logic. I'm pretty sure this has been asked before, but I can't find a good dupe target. – user2357112 Dec 20 '16 at 05:04
  • It looks like it's possibly related to [this issue](https://bugs.python.org/issue1580) – mgilson Dec 20 '16 at 05:09
  • yes t @mgilson you are right :) – Prem Narain Dec 20 '16 at 05:17
  • printing is not showing you all the digits. [link](http://stackoverflow.com/questions/13345334/strange-behaviour-with-floats-and-string-conversion) – minji Dec 20 '16 at 05:19
  • You should go read up on the differences between Python2 and Python3. – SudoKid Dec 20 '16 at 05:27
  • Possible duplicate of _[Floating point behavior in Python 2.6 vs 2.7](http://stackoverflow.com/questions/20643386/floating-point-behavior-in-python-2-6-vs-2-7)_. – Christian Dean Dec 20 '16 at 05:28
  • yes i got my answer from [this link](http://stackoverflow.com/questions/20643386/floating-point-behavior-in-python-2-6-vs-2-7) – Prem Narain Dec 20 '16 at 05:28

2 Answers2

3

It is not due to the change in the print but changes in the __str__ function of floats which print implicitly calls. Hence, when you do print, it makes a call like:

# For Python 2.7
>>> print (1.2 - 1.0).__str__()
0.2

In order to display the floating values as it is, you may explicitly call .__repr__ as:

>>> print (1.2 - 1.0).__repr__()
0.19999999999999996

For more details, check Martjin's answer on Floating point behavior in Python 2.6 vs 2.7 which states:

In Python 2.7 only the representation changed, not the actual values. Floating point values are still binary approximations of real numbers, and binary fractions don't always add up to the exact number represented.

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

print in Python2.7 rounds float numbers. Actually, the numbers 1.2 and 0.2 can't be represented exactly in memory (they are infinite fractions in the binary code). Therefore in order to output it correctly some output functions in programming languages may use the round. print in Python2.7 uses the round, but print in Python3.x doesn't.

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95