Unexpected Results for sin and cos Functions with Degrees Input
When utilizing the C/C sin() and cos() functions for angles expressed in degrees, discrepancies may arise from the mathematical interpretation of degrees versus radians.
Cause of Discrepancy
C/C 's sin() and cos() functions are designed to accept angles in radians. However, the subsequent use of the DegreesToRadians() function to convert degrees to radians introduces inherent approximation due to rounding and the finite precision limits of the double datatype. Additionally, the use of M_PI may result in slight deviations from the mathematical definition of π.
Mathematical Interpretation
sin(0.0547) = 0.0547
cos(0.0547) = 0.9984
When expressed in degrees:
sin(0.0547) = sin(0.0547 × 180 / π) ≈ 0.0031
cos(0.0547) = cos(0.0547 × 180 / π) ≈ 0.9995
Solution
To address this discrepancy, we recommend reducing the angle in degrees prior to invoking the trigonometric functions. This technique ensures precision within a range of -45° to 45°.
#define M_PIf (3.14159265358979323846) #include <stdio.h> double DegreesToRadians(double degrees) { return degrees * M_PIf / 180; } double sind(double x) { if (x < 0.0) { return -sind(-x); } int quo; double x90 = remquo(fabs(x), 90.0, &quo); switch (quo % 4) { case 0: return sin(DegreesToRadians(x90)); case 1: return cos(DegreesToRadians(x90)); case 2: return sin(DegreesToRadians(-x90)); case 3: return -cos(DegreesToRadians(x90)); } }
Sample Output
Using the improved sind() function:
printf("sin() of 180.0 degrees: %f\n", sin(DegreesToRadians(180.0))); printf("sind() of 180.0 degrees: %f\n", sind(180.0));
Output
sin() of 180.0 degrees: -1.2246467991474805e-16 sind() of 180.0 degrees: -0.0000000000000000e+00
This output demonstrates accurate results for the sin() and cos() functions with angles given in degrees.
The above is the detailed content of Why Do C/C \'s `sin()` and `cos()` Functions Produce Unexpected Results When Using Degrees?. For more information, please follow other related articles on the PHP Chinese website!