Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point precision while using Python's max()

Why so?

>>> max(2, 2.01)
2.0099999999999998
like image 430
Jibin Avatar asked Feb 13 '26 06:02

Jibin


1 Answers

The number 2.01 represented in binary is:

b10.00000010100011111100001010001111110000101000111111000010100011111100...

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

b10.000000101000111111000010100011111100001010001111110

Expressed in decimal, this number is exactly:

2.0099999999999997868371792719699442386627197265625

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

2.0099999999999998
like image 155
Stephen Canon Avatar answered Feb 14 '26 19:02

Stephen Canon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!