Ekanshdeep Gupta
Ekanshdeep Gupta

Reputation: 182

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)

Upvotes: 3

Views: 283

Answers (1)

pts
pts

Reputation: 87281

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')

Upvotes: 11

Related Questions