Home >Backend Development >C++ >Why Do C/C \'s `sin()` and `cos()` Functions Produce Unexpected Results When Using Degrees?

Why Do C/C \'s `sin()` and `cos()` Functions Produce Unexpected Results When Using Degrees?

DDD
DDDOriginal
2024-11-29 20:37:12254browse

Why Do C/C  's `sin()` and `cos()` Functions Produce Unexpected Results When Using Degrees?

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, &amp;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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn