Python round off error

python, python-2.7

Solution

Aside from @Ashwini Chaudhary answer,

Question :

Why is python adding up the trailing 00000000002 when mathematically it is not supposed to be there

Answer :

Because value in the machine is not exact. It's not a bug in Python or the bug in your code either. You will see this exact same problem in all languages that support binary floating-point arithmetic. However, different languages may display it differently (round-off).

Try this:

0.1 + 0.2

You will get

0.30000000000000004

This is because `0.1` can't be represent in Binary form exactly. In base 2, or Binary, `0.1` is the infinity repeating numbers

0.0001100110011001100110011001100110011001100110011...

So, Python decided to round this off instead.

I suggest you read more here.

Problem

I was just using python as a calc and I saw this ``` Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 62 * 41.2 * 2 / 250 20.435200000000002 >>> 62 * 4.12 * 2 / 25 20.4352 >>> ``` Just to be sure I fired the following code through gcc but that did not show me the above behaviour. I understand this is potentially something with rounding off, but it should then be uniform. Why is python adding up the trailing 00000000002 when mathematically it is not supposed to be there. C/C++ code ``` #include <stdio.h> int main () { printf ("%lf %lf \n", 62 * 41.2 * 2 / 250, 62 * 4.12 * 2 / 25); } ``` results in 20.435200 20.435200 If someone is curious about the particular numbers they belong to some engine displacement computation comparisons :)

Original source

Related problems