Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert degrees to radians?

I have the following function to convert from radians to degrees:

float DegreesToRadians(float degrees) {
    return degrees * (PI / 180);
}

When I now do:

sinf(DegreesToRadians(90));

This returns 1, as expected. But when I do:

sinf(DegreesToRadians(180));

It returns -8.74228e-08. Does anybody know why this is happening? (This happens with cosf too, but in reverse: 180 -> -1; 90 -> -8.74228e-08)

like image 402
Ams1901 Avatar asked Sep 15 '25 21:09

Ams1901


2 Answers

How do I convert degrees to radians?

OP's degrees to radians conversion is reasonable.

return degrees * (PI / 180);

when I do: sinf(DegreesToRadians(180)); It returns -8.74228e-08.

This does not meet OP's expectations as degrees * (PI / 180) was not done exactly given PI is not π @Andy Turner. PI is machine pi, a nearby representable value of π. π is an irrational number. All finite floating point values are rational. There is no way to do non_zero_degrees * (π / 180) exactly. The error in the approximations are amplified in the sinf() call.

sinf(DegreesToRadians(180)) does not result in sine(π), but sine(PI). PI is close to π, but not the same. double graphical example.


Instead, reduce the range of of the angle in degrees first to maintain accuracy with trigonometric identities.

Example

like image 82
chux - Reinstate Monica Avatar answered Sep 18 '25 17:09

chux - Reinstate Monica


Well, your PI is an approximation of the real mathematical constant. Then your degree-to-radian conversion is an approximation of the real conversion because floating point math is an approximation. And then, the standard sinf function approximates the sin function in math. Thus, you should expect your results to be approximate. -8.74228e-08 is a number close to 0. It's an approximation.

like image 35
Ayxan Haqverdili Avatar answered Sep 18 '25 18:09

Ayxan Haqverdili