Is this a division bug in Python?

I was following along with a Python Coursera course on beginning Python and one of the test modules asked us to do some simple division. While coding the practice portion I noticed a strange thing that happened with Python division that seems to indicate a problem with how Python handles simple division.

When I try to get the result of (243 * 0.65) in Python, I seem to get an incorrect answer. The answer seems like it should be 157.95 but the answer that Python returned is 157.95000000000002.

The same thing happens when I tried (298 * 0.65), but not when I try (325 * 0.65).

Now this is probably because I am completely new to Python and I have done something strange, or I have misunderstood something, but it is just a simple, one line, division statement.

Can anyone explain this to me?

Here’s an article about this phenomenon:

1 Like

So this problem is caused because computers are not base 10, and must approximate base 10 calculations/numbers using base 2 numbers?

Short answer: Yes, exactly.

Slightly longer answer: It’s not that Python (or any other programming languages) can’t do base 10, but base 2 is much more efficient, and is therefore the default since most of the time the error doesn’t matter anyway.

1 Like

Thank you!

If you did want to get the precise result, use the fractions standard-library module

>>> from fractions import Fraction
>>> a = 243
>>> b = Fraction(65, 100)  # 0.65 = 65/100
>>> float(a * b)

Thanks Laurie O!