Floating-point precision when using Python max ()

Why is that?

>>> max(2, 2.01) 2.0099999999999998 
+2
source share
4 answers

The number 2.01, presented in binary format:

 b10.00000010100011111100001010001111110000101000111111000010100011111100... 

The computer uses only a finite number of digits to store floating point values, but a binary representation of 2.01 requires an infinite number of digits; as a result, it is rounded to the nearest representable value:

 b10.000000101000111111000010100011111100001010001111110 

In decimal terms, this number is exactly:

 2.0099999999999997868371792719699442386627197265625 

When you print it, it is rounded a second time to seventeen decimal digits, giving:

 2.0099999999999998 
+5
source

Floating-point numbers do not encode exact values, but rather approximate. The result is essentially the next nearest floating point number to the actual number you entered.

http://docs.python.org/tutorial/floatingpoint.html

+3
source

because:

 >>> 2.01 2.0099999999999998 

this is a way to store floating point numbers

+2
source

Rounding floating point. His attempt is to say 2.01, but cannot express it exactly as a floating point number, so he does his best.

0
source

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


All Articles