Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.cos(Math.PI/2) returns 6.123031769111886e-17 in JavaScript & AS3?

If I'm understanding this correct, both JavaScript and ActionScript 3 works with radians.

So the expected output of the following codes would be:

Math.PI                 //Expected 3.141592653589793, got 3.141592653589793

Math.sin(0)             //Expected 0, got 0
Math.sin(Math.PI/2)     //Expected 1, got 1
Math.sin(Math.PI)       //Expected 0, got 1.2246063538223773e-16
Math.sin(Math.PI*3/2)   //Expected -1, got -1
Math.sin(Math.PI*2)     //Expected 0, got -2.4492127076447545e-16

Math.cos(0)             //Expected 1, got 1
Math.cos(Math.PI/2)     //Expected 0, got 6.123031769111886e-17
Math.cos(Math.PI)       //Expected -1, got -1
Math.cos(Math.PI*3/2)   //Expected 0, got -1.836909530733566e-16
Math.cos(Math.PI*2)     //Expected 1, got 1

This is the same behavior in Firefox, Chrome, Safari and also in Flash Professional CS5.5. I'm using Mac OS X 10.7.2.

Test:

http://jsfiddle.net/KA4VM/

like image 219
Tyilo Avatar asked Nov 08 '11 12:11

Tyilo


People also ask

What does math Cos do in JS?

The Math. cos() static function returns the cosine of the specified angle, which must be specified in radians.

How do you calculate pi in JavaScript?

To get the value of PI in JavaScript, use the Math. PI property. It returns the ratio of the circumference of a circle to its diameter, which is approximately 3.14159.

How do I get cosine in JavaScript?

The Javascript cos() method returns the numeric value between -1 and 1, representing the cosine of an angle given in radians. To find the cosine value of a given argument in JavaScript, the Math. cos() method is used.

Does Math Cos return radians or degrees?

cos() returns the cosine of a number (radians) that is sent as a parameter.


1 Answers

Have you looked at the value you're getting? You're expecting 0, but you're getting something like

0.00000000000000012246063538223773

Isn't that close enough to zero for you?

Basically, you shouldn't expect binary floating point operations to be exactly right when your inputs can't be expressed as exact binary values - which pi/2 can't, given that it's irrational. (You shouldn't expect the results to be exact even when the inputs can be expressed exactly in binary, if the output can't be expressed exactly...)

like image 157
Jon Skeet Avatar answered Sep 20 '22 06:09

Jon Skeet