Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Math.cos and Math.sin are inaccurate. Is there any solution?

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?

like image 319
tomas.teicher Avatar asked Jun 03 '11 06:06

tomas.teicher


People also ask

How is sin calculated in Javascript?

sin() The Math. sin() function returns the sine of a number in radians.

How do I get cosine in Javascript?

The Math. cos() method returns the cosine of a number. The Math. cos() method returns a number between -1 and 1.

Does Math Cos take degrees or radians?

The cosine is equal to the ratio of the side adjacent to the angle and the hypotenuse of the right-angled triangle they define. The angle must be measured in radians.

What is math Cos in Javascript?

The Math. cos() method is used to return the cosine of a number. The Math. cos() method returns a numeric value between -1 and 1, which represents the cosine of the angle given in radians.


1 Answers

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.

like image 169
Andrew Cooper Avatar answered Nov 14 '22 03:11

Andrew Cooper