cos of degrees not matching the cos of equivalent radians

SamGoody picture SamGoody · Sep 19, 2010 · Viewed 7.6k times · Source

All math functions in JavaScript use radians in place of degrees. Yet they are either unequal, or I am way off base.

The conversion from degrees to a radian is:

var rad = angle * Math.PI / 180

A 90 degree angle equals 1.57079633 radian

The cosine of a 90 degree angle equals 0.
The cosine of a 1.57079633 radian equals -3.20510345 × 10-9.

Note that in the Javascript, everything is done in one step to avoid rounding errors:

var cos = Math.cos(angle * Math.PI / 180);

I am obviously missing something obvious here, but boy is it screwing up the code.

Answer

Jon Skeet picture Jon Skeet · Sep 19, 2010

everything is done in one step to avoid rounding errors

How does that avoid rounding errors? It just means that the rounding errors aren't available in a separate variable, that's all.

The true value of pi can't be accurately represented as a floating point number, so the true value of pi / 2 can't either. So you can't give Math.cos the exact value needed to get 0. But hey - 10-9 is a very, very small number. It means that if you were drawing a line 10,000 kilometres long, you'd end up veering 1cm away from the relevant axis.

This is exactly the kind of thing you should expect when dealing with floating point numbers. Don't compare with equality - compare within some tolerance.