Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, why does math.floor(4.9999999999999999) == 5?

I know this is some floating point error, but I had read that python has infinite precision, so this kind of thing shouldn't happen.

Self contained runnable code:

import math
math.floor(4.9999999999999999)
like image 742
Ekanshdeep Gupta Avatar asked Jul 26 '26 20:07

Ekanshdeep Gupta


1 Answers

It's rounded up to 5.0 before math.floor is called.

>>> 4.9999999999999999 == 5.0
True
>>> import math
>>> math.floor(5.0)
5.0

One way to get correct behavior is using Decimal (and not using float or math at all):

>>> import decimal
>>> int(decimal.Decimal('4.99999999999999999999999999999999999999999999999999999999999999999999999'
).to_integral(rounding=decimal.ROUND_DOWN))
4

FYI The Python float type is an IEEE 754 64-bit float, thus it can have (at most) 2**64 different values. The decimal constant 4.9999999999999999 cannot be represented exactly, so it's rounded to some other value (which happens to be the exact representation of 5.0) when Python parses the source code. Without the quotes, the float is rounded before it gets converted to Decimal:

>>> import decimal
>>> decimal.Decimal(4.9999999999999999)
Decimal('5')
>>> decimal.Decimal('4.9999999999999999')
Decimal('4.9999999999999999')
like image 86
pts Avatar answered Jul 28 '26 10:07

pts



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!