Reputation: 6819
When evaluating Math.sin(Math.PI)
in JavaScript, the result is 1.2246063538223773e-16
rather than 0
. I suppose this is due to the limited precision of the JavaScript Number
and limited precision of the sinus algorithm.
How could one prevent these round off errors? Would it help to use a BigNumber type with higher precision, and a higher precision sinus algorithm? Or would that just give you a smaller round-off error but still an error?
Upvotes: 1
Views: 1387
Reputation: 25682
Use Math.sin(Math.PI).toFixed(2)
, the parameter of .toFixed
is the precision you need.
Unfortunately, IEEE 754 is not perfect and also the memory is limited... The same happens when you: 0.1 + 0.2 == 0.30000000000000004
You should be aware that the result of .toFixed(precision)
is string, so you may need to:
parseFloat(Math.sin(Math.PI).toFixed(2));
Upvotes: 1
Reputation: 3163
I use Number.EPSILON to sort out rounding errors. This is mostly supported but the linked page has a polyfill for IE
var sinTheta = Math.sin(theta);
if (Math.abs(sinTheta) < Number.EPSILON) {
sinTheta = 0;
}
Upvotes: 4