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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With