Jos de Jong
Jos de Jong

Reputation: 6819

How to prevent round-off error with Math.sin(Math.PI)?

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

Answers (2)

Minko Gechev
Minko Gechev

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

Luke H
Luke H

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

Related Questions