Why is decimal multiplication slightly inaccurate?

Question:

Why does this happen in Python:

>>> 
>>> 483.6 * 3
1450.8000000000002
>>> 

I know this happens in other languages, and I’m not asking how to fix this. I know you can do:

>>> 
>>> from decimal import Decimal
>>> Decimal('483.6') * 3
Decimal('1450.8')
>>> 

So what exactly causes this to happen? Why do decimals get slightly inaccurate when doing math like this?

Is there any specific reason the computer doesn’t get this right?

Asked By: jackcogdill

||

Answers:

See the Python documentation on floating point numbers. Essentially when you create a floating point number you are using base 2 arithmetic. Just as 1/3 is .333…. on into infinity, so most floating point numbers cannot be exactly expressed in base 2. Hence your result.

The difference between the Python interpreter and some other languages is that others may not display these extra digits. It’s not a bug in Python, just how the hardware computes using floating-point arithmetic.

Answered By: Kyle

Computers store numbers as bits (in binary). Unfortunately, even with infinite memory, you cannot accurately represent some decimals in binary, for example 0.3. The notion is a kin to trying to store 1/3 in decimal notation exactly.

Answered By: Volatility

Computers can’t represent every floating point number perfectly.

Basically, floating point numbers are represented in scientific notation, but in base 2. Now, try representing 1/3 (base 10) with scientific notation. You might try 3 * 10-1 or, better yet, 33333333 * 10-8. You could keep adding 3’s, but you’d never have an exact value of 1/3. Now, try representing 1/10 in binary scientific notation, and you’ll find that the same thing happens.

Here is a good link about floating point in python.

As you delve into lower level topics, you’ll see how floating point is represented in a computer. In C, for example, floating point numbers are represented as explained in this stackoverflow question. You don’t need to read this to understand why decimals can’t be represented exactly, but it might give you a better idea of what’s going on.

Answered By: Joshua Kravitz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.