Search code examples
javamathpython-2.7roundingparentheses

Using parenthesis causes decimal errors on Python and Java


I was recently debugging a program that consistently returned errors just a few decimal points off. It turns out the error was on the very line I believed that I didn't need to check: 999999 * (.18 / 12).

I knew the parenthesis were not necessary because mathematically, the expression should evaluate to the same answer regardless of their presence, but I included them just for clarity. When I typed the statement into the Python interpreter, however, it returned 14999.98499999999, while the correct answer should be 14999.985. When I removed the parenthesis and typed 999999 * .18 / 12, I got the correct answer (14999.985). Just to make sure it wasn't just a Python thing, I tried it with Java too, same answer.

Why is this? I understand that computers can't store fractions as exact values, so some degree of error is to be expected, but what's the difference in the way the computer evaluates those two statements?

TL;DR: 999999 * (.18 / 12) gives me a different answer than 999999 * .18 / 12 when mathematically, they should both evaluate to 14999.985. Why?


Solution

  • You are better off doing a multiply before a divide. Since a divide has a lesser probable chance of being represented correctly as compared to a overflow happening during multiplication.