accuracy of sinl and cosl function in c++

180 Views Asked by At

I want an accuracy of about 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;
}

Here is the code segment which I am using I am using the function rotate_point to rotate a point about a given pivot, here cx, cy are the pivots, point is the point to rotate in clockwise direction, angle is the angle passed in degrees (I cant pass it in radians assume that). My problem is when I call the function with values rotate_point(50,50,25, p) where p.x=50 p.y=100 then expected output is x=100 y=50.

I am getting x=99.99999000666841262458 y=49.96838777042233631365, x is ok but y is not in desired accuracy range.

1

There are 1 best solutions below

0
On BEST ANSWER

Do not use the value

pi = 22 / 7

if you want accuracy. Please use

M_PI

which is defined in math.h. In MSVC you also need

#define _USE_MATH_DEFINES

to make the following values available.

#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)