简体   繁体   English

用x轴计算角度的最快方法

[英]fastest way to compute angle with x-axis

What is the fastest way to calculate angle between a line and the x-axis? 计算直线和x轴之间角度的最快方法是什么?

I need to define a function, which is Injective at the PI:2PI interval (I have to angle between point which is the uppermost point and any point below). 我需要定义一个函数,它在PI:2PI间隔是Injective(我必须在最高点和下面的任何点之间的角度)。

PointType * top = UPPERMOST_POINT;
PointType * targ = TARGET_POINT;

double targetVectorX = targ->x - top->x;
double targetVectorY = targ->y - top->y;

first try 第一次尝试

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

second try 第二次尝试

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

I do not need the angle directly (radians or degrees), just any value is fine as far as by comparing these values of this kind from 2 points I can tell which angle is bigger. 我不需要直接角度(弧度或度数),只要通过比较这种值从2点我可以判断哪个角度更大,任何值都可以。 (for example angle in example one is between -1 and 1 (it is cosine argument)) (例如,示例1中的角度介于-1和1之间(它是余弦参数))

I just wrote Fastest way to sort vectors by angle without actually computing that angle about the general question of finding functions monotonic in the angle, without any code or connections to C++ or the likes. 我刚刚编写了最快的方法来按角度对矢量进行排序,而没有实际计算角度中找到函数单调的一般问题的角度,没有任何代码或与C ++或类似的连接。 Based on the currently accepted answer there I'd now suggest 基于目前接受的答案,我现在建议

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

The great benefit compared to the currently accepted answer here is the fact that you won't have to worry about infinite values, since all non-zero vectors (ie targetVectorX and targetVectorY are not both equal to zero at the same time) will result in finite pseudoangle values. 目前接受的答案相比,最大的好处是您不必担心无限值,因为所有非零向量(即targetVectorXtargetVectorY不会同时等于零)将导致有限伪角值。 The resulting pseudoangles will be in the range [−2 … 2] for real angles [−π … π], so the signs and the discontinuity are just like you'd get them from atan2 . 对于实际角度[-π...π],得到的伪角将在[-2 ... 2]的范围内,因此符号和不连续性就像你从atan2得到它们一样。

Check for y being zero as atan2 does; 检查y是否为atan2; then The quotient x/y will be plenty fine. 然后商x / y会很好。 (assuming I understand you correctly). (假设我理解正确)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM