Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cos of degrees not matching the cos of equivalent radians

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.

like image 833
SamGoody Avatar asked Sep 19 '10 12:09

SamGoody


2 Answers

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.

like image 167
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet


There will always be rounding errors. And floating point isn't mathematically accurate anyways, it's only accurate to a certain amount of significant digits.

Change your code so that it doesn't "screw up" when you have errors in the order of 1/1000000000.

like image 34
Matti Virkkunen Avatar answered Sep 29 '22 02:09

Matti Virkkunen