Trigonometric functions in JavaScript do not work?

I don’t understand why I get very strange values ​​from trigonometric functions in JavaScript. For instance:

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 on Mozilla and Chrome and got the same result. It seems that the parameter of a trigonometric function is too accurate.

Please, help!

+4
source share
1 answer

you can use Number.EPSILON

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

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

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));
Run codeHide result

, :

+1

Source: https://habr.com/ru/post/1690973/


All Articles