最快的方法来计算角度与x轴

fastest way to compute angle with x-axis

本文关键字:计算 方法      更新时间:2023-10-16

计算直线与x轴夹角的最快方法是什么?

我需要定义一个函数,它在PI:2PI区间内内射(我必须在最上面的点和下面的任何点之间夹角)

PointType * top = UPPERMOST_POINT;
PointType * targ = TARGET_POINT;
double targetVectorX = targ->x - top->x;
double targetVectorY = targ->y - top->y;

第一次尝试

//#1
double magnitudeTarVec = sqrt(targetVectorX*targetVectorX + targetVectorY*targetVectorY);
angle = tarX / magTar;

第二次尝试

//#2 slower
angle = atan2(targetVectorY, targetVectorX);

我不需要直接的角度(弧度或度),只要从两个点比较这些值,我就可以知道哪个角度更大。(例如例1中的角度介于-1和1之间(它是余弦参数))

检查y是否像atan2一样为零;那么商x/y就很好了。(假设我没理解错)。

我刚刚写了最快的方法来排序向量的角度没有实际计算角度的一般问题,寻找函数单调的角度,没有任何代码或连接到c++或类似的。根据目前接受的答案,我现在建议

double angle = copysign( // magnitude of first argument with sign of second
  1. - targetVectorX/(fabs(targetVectorX) + fabs(targetVectorY)),
  targetVectorY);

与目前接受的答案相比,最大的好处是您不必担心无限值,因为所有非零向量(即targetVectorXtargetVectorY不同时等于零)将导致有限的伪角值。对于实角[−π…π],得到的伪角将在[−2…2]范围内,因此符号和不连续就像你从atan2中得到的那样。