Home >Backend Development >C++ >Why Are C/C \'s `sin()` and `cos()` Functions Inaccurate for Familiar Angles?
Unexpected Results from sin and cos for Familiar Angles
When using C/C 's sin() and cos() functions with an angle of 180 degrees, users may encounter unexpected results. The expected values are:
However, the obtained values often deviate from these expectations:
Explanation
C/C 's sin() and cos() functions operate with radians as input parameters, not degrees. Although DegreesToRadians() attempts to convert degrees to radians, rounding inaccuracies and limited double() precision can lead to discrepancies in the results. Additionally, the machine constant M_PI, an estimation of the mathematical constant π, may contribute to these deviations.
Solution
To address these inaccuracies, it is recommended to perform angle reduction in degrees before calling the trigonometric functions. This involves reducing the angle to within a range of -45° to 45° prior to invoking sin(). This ensures that large values of N in calculations like sin(90.0*N) produce accurate results of -1.0, 0.0, and 1.0.
A sample code demonstrating this approach is provided:
#include <math.h> #include <stdio.h> static double d2r(double d) { return (d / 180.0) * ((double) M_PI); } double sind(double x) { if (!isfinite(x)) { return sin(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(d2r(x90)); case 1: return cos(d2r(x90)); case 2: return sin(d2r(-x90)); case 3: return -cos(d2r(x90)); } return 0.0; }
This updated code produces more accurate results for various angles, as demonstrated by its output:
sin() of -90.0 degrees is 2.4492935982947064e-16 sind() of -90.0 degrees is -0.0000000000000000e+00 sin() of -120.0 degrees is -7.0710678118654752e-01 sind() of -120.0 degrees is -7.0710678118654746e-01 sin() of -135.0 degrees is -0.70710678118654757 sind() of -135.0 degrees is -0.70710678118654762 sin() of -150.0 degrees is -2.4492935982947064e-16 sind() of -150.0 degrees is -0.0000000000000000e+00 sin() of -180.0 degrees is 2.4492935982947064e-16 sind() of -180.0 degrees is -0.0000000000000000e+00
The above is the detailed content of Why Are C/C \'s `sin()` and `cos()` Functions Inaccurate for Familiar Angles?. For more information, please follow other related articles on the PHP Chinese website!