Search code examples
javascriptmath

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


JavaScript Math trigonometrical methods return wrong results.

alert(Math.sin(Math.PI));
// sin(180) in degrees should return 0, but above code doesn't

it doesn't return 0.

Maybe problem is with JavaScript decimal number precision. Is there any workaround to get correct results?


Solution

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