Why such a weird python?

My code is:

#!/usr/bin/python # -*- coding: utf-8 -*- print (round(1.555,1)) #It seems normal print (round(1.555,2)) #Why it is not output 1.56? print (round(1.556,2)) #It seems normal 

Conclusion:

 sam@sam :~/code/python$ ./t2.py 1.6 1.55 1.56 sam@sam :~/code/python$ 

round(1.555,1) outputs 1.6 .

Why not round(1.555,2) output 1.56 ?

+6
source share
3 answers

See the documentation :

Note The behavior of round() for floats may be unexpected: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68 . This is not a mistake: it is the result of the fact that most decimal fractions cannot be represented exactly as a float. See Floating Point Arithmetic: Problems and Limitations for more information.

If you keep digging (i.e. click this link), you will find an example similar to yours:

The documentation for the built-in round() function states that it rounds to the nearest value, rounding off ties from zero. Since the 2.675 decimal is halfway between 2.67 and 2.68 , you can expect the result here to be (binary approximation) 2.68 . It is not, because when the decimal string 2.675 converted to a binary floating-point number, it is again replaced by a binary approximation whose exact value is

 2.67499999999999982236431605997495353221893310546875 

Formatting strings will also not fix your problem. The floating point number simply does not persist as you expected:

 >>> '{:0.2f}'.format(1.555) '1.55' 

This is actually not a β€œfix”, but Python has a decimal module that is designed for floating point arithmetic:

 >>> from decimal import Decimal >>> n = Decimal('1.555') >>> round(n, 2) Decimal('1.56') 
+10
source

Directly from the docs:

The behavior of round () for float may be unexpected: for example, the round (2,675, 2) gives 2.67 instead of the expected 2.68. This is not a mistake: it is the result of the fact that most decimal fractions cannot be represented exactly as a float. See Floating-Point Arithmetic: Problems and Limitations for more information.

+6
source

From http://docs.python.org/2/library/functions.html#round :

Note

The behavior of round () for float may be unexpected: for example, round (2.675, 2) gives 2.67 instead of the expected 2.68. This is not a mistake: it is the result of the fact that most decimal fractions cannot be represented exactly as floats. See Floating-Point Arithmetic: Problems and Limitations for more information.

0
source

All Articles