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

If I ran the following python2.7 console, it gave me the output:

>>> 1.2 - 1.0 0.19999999999999996 >>> print 1.2 - 1.0 0.2 

While I perform the 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 the python2.7.12 print instruction giving me only 0.2, but in the python3.5.2 print function giving me 0.19999999999999996.

+5
source share
2 answers

This is not due to a change in print , but to a change in the __str__ floats function, which prints implicitly calls. Therefore, when you type, it calls a call:

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

To display floating values ​​as is, you can explicitly call .__repr__ as:

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

See Martjin's answer on floating point behavior in Python 2.6 vs 2.7 , which says:

In Python 2.7, only the view has changed, not the actual values. Floating-point values ​​are still binary approximations of real numbers, and binary fractions do not always coincide with the exact number.

+3
source

print in Python2.7 floating-point numbers. In fact, the numbers 1,2 and 0,2 cannot be represented exactly in memory (they are infinite fractions in binary code). Therefore, to correctly output it, some output functions in programming languages ​​can use a round. print in Python2.7 uses the round, but print in Python3.x does not.

0
source

Source: https://habr.com/ru/post/1261544/


All Articles