Saturday, 1 February 2014

Is JavaScript's Floating-Point Math Broken?

All floating point math is like this and is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double.
You need to never compare with == but instead compare the absolute value of their differences, and make sure that this difference is smaller than the Epsilon value, which is a very very small number.
x = 0.2;
y
= 0.3;
equal
= (Math.abs(x - y) < 0.000001)
For the exact reason why, please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
For a javascript library implementing algorithms from the source, consider sinful.js

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More