欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算两个向量的夹角

程序员文章站 2022-03-31 23:02:13
...
double getRotateAngle(double x1, double y1, double x2, double y2)
{
    const double epsilon = 1.0e-6;
    const double nyPI = acos(-1.0);
    double dist, dot, degree, angle;
 
 // normalize
    dist = sqrt( x1 * x1 + y1 * y1 );
    x1 /= dist;
    y1 /= dist;
    dist = sqrt( x2 * x2 + y2 * y2 );
    x2 /= dist;
    y2 /= dist;
// dot product
    dot = x1 * x2 + y1 * y2;
    if ( fabs(dot-1.0) <= epsilon )
    angle = 0.0;
    else if ( fabs(dot+1.0) <= epsilon )
    angle = nyPI;
    else {
        double cross;
 
        angle = acos(dot);
  //cross product
        cross = x1 * y2 - x2 * y1;
  // vector p2 is clockwise from vector p1
  // with respect to the origin (0.0)
        if (cross < 0 ) {
            angle = 2 * nyPI - angle;
        }
    }
    degree = angle *  180.0 / nyPI;
    return degree;
}