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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With