Javascript Math trigonomerial methos return wrong results. Try
alert(Math.sin(Math.PI));
it doesn't return 0.
Maybe problem is with javascript decimal number precision. Is there any workoround to get correct results?
Javascript Math trigonomerial methos return wrong results. Try
alert(Math.sin(Math.PI));
it doesn't return 0.
Maybe problem is with javascript decimal number precision. Is there any workoround to get correct results?
It's very, very close to zero, though. (~ 10^-16)
And alert(Math.sin(Math.PI/2))
does return 1
.
It's just one of things you have to be careful of when dealing with floating point arithmetic. Rounding errors pop up all over the place.
you can use
Math.sin(Math.PI).toFixed(3) // "0.000"
const cos = (a) => Math.cos(Math.PI * a / 180);
cos(90) // 6.123233995736766e-17
then you can use .toFixed()
cos(90).toFixed(3) // "0.000"
.toFixed()
returns string, so you can parse it to float using parseFloat()
parseFloat(cos(90).toFixed(3)) // 0.000