Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the print function in Python3 round a decimal number? [duplicate]

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.

like image 462
Prem Narain Avatar asked Oct 18 '22 20:10

Prem Narain


1 Answers

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.

like image 50
Moinuddin Quadri Avatar answered Oct 20 '22 09:10

Moinuddin Quadri