javascriptflashactionscript-3ecmascript-5

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/


Solution

  • 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...)

    Note that while this is expressed in terms of binary floating point, decimal floating point systems have the same problem: fundamentally, if you can't express the inputs/outputs precisely in your chosen type system, you're not going to get precise arithmetic.