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/
The Math. cos() static function returns the cosine of the specified angle, which must be specified in radians.
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.
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.
cos() returns the cosine of a number (radians) that is sent as a parameter.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With