Nejc Jezersek
Nejc Jezersek

Reputation: 719

Trigonometric functions in JavaScript not working?

I don't understand, why I get some very strange values from trigonometric functions in JavaScript. For example:

Math.sin(Math.PI); // returns 1.2246467991473532e-16, but should return 0
Math.cos(Math.PI/2); // returns 6.123233995736766e-17, but should return 0
Math.sin(3.14); // returns 0.0015926529164868282, whitch is ok but
Math.sin(3.141592); // returns 6.535897930762419e-7!

I tried this in Mozilla and Chrome and got the same result. It seems the parameter of the trigonometric function is too precise.

Please help!

Upvotes: 4

Views: 748

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386530

You could use Number.EPSILON

The Number.EPSILON property represents the difference between 1 and the smallest floating point number greater than 1.

and take the absolute delta of the value and wanted value and check if it is smaller than the Number.EPSILON. If true, then the value's error is smaller than the possible error of floating point arithmetic.

console.log([
    [Math.sin(Math.PI), 0], 
    [Math.cos(Math.PI/2), 0],
    [Math.sin(3.14), 0.0015926529164868282],
    [Math.sin(3.141592), 6.535897930762419e-7]
].map(([a, b]) => Math.abs(a - b) < Number.EPSILON));

Some more to read about the problem with limited digital representation of floating point values:

Upvotes: 1

Related Questions