Sinl 和 Cosl 函数在 C++ 中的准确性

accuracy of sinl and cosl function in c++

本文关键字:准确性 C++ Cosl 函数 Sinl      更新时间:2023-10-16

我想要大约 0.000001 的准确度。

typedef struct p {
    long double x;
    long double y;
}point;
point rotate_point(long double cx,long double cy,long double angle,point p) //pivot then angle then point to rotate
{ // cout<<"ncx="<<cx<<"cy="<<cy<<"x="<<p.x<<"y="<<p.y;
    angle=(angle/100)*pi*2;

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;
  cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(20);
  // rotate point
  long double xnew = p.x * cosl(-angle) - p.y * sinl(-angle);
  long double ynew = p.x * sinl(-angle) + p.y * cosl(-angle);
  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
   cout<<"x="<<p.x<<"y="<<p.y;
  return p;
}

这是我正在使用的代码段,我正在使用函数rotate_point围绕给定枢轴旋转一个点,这里cxcy是枢轴,point是顺时针方向旋转的点,angle是以度为单位传递的角度(我不能以弧度假设的那样传递它)。我的问题是当我调用带有值的函数时rotate_point(50,50,25, p)其中p.x=50 p.y=100则预期输出为 x=100 y=50

我正在x=99.99999000666841262458 y=49.96838777042233631365x还可以,但y不在所需的精度范围内。

不要使用值

pi = 22 / 7

如果你想要准确性。请使用

M_PI

math.h 中定义。在 MSVC 中,您还需要

#define _USE_MATH_DEFINES

以使以下值可用。

#define M_E        2.71828182845904523536   // e
#define M_LOG2E    1.44269504088896340736   // log2(e)
#define M_LOG10E   0.434294481903251827651  // log10(e)
#define M_LN2      0.693147180559945309417  // ln(2)
#define M_LN10     2.30258509299404568402   // ln(10)
#define M_PI       3.14159265358979323846   // pi
#define M_PI_2     1.57079632679489661923   // pi/2
#define M_PI_4     0.785398163397448309616  // pi/4
#define M_1_PI     0.318309886183790671538  // 1/pi
#define M_2_PI     0.636619772367581343076  // 2/pi
#define M_2_SQRTPI 1.12837916709551257390   // 2/sqrt(pi)
#define M_SQRT2    1.41421356237309504880   // sqrt(2)
#define M_SQRT1_2  0.707106781186547524401  // 1/sqrt(2)