Changing Order Of Operation May Give Wrong Results in Javascript

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In math, the associative property for addition says that …

(x + y) + z == x + ( y + z )

is a true statement.  However, due to round-off errors, Javascript does not always obey this rule.

Take a look at this example…

wrong results

wrong results

The console.log outputs two different (although close) results.  Hence the comparison results in false and outputs “They are not equal”, when in math they should be equal.

Depending on the nature of your application, a “close enough” comparison like the following may suffice …

close enough comparison

close enough comparison

This says that if the two results are within 0.00000001%, then they are close enough.  The value 1e-10 is 0.0000000001.  So the above run will result in “They are close enough”.