3

What is the fastest way to calculate angle between a line and the x-axis?

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

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. (for example angle in example one is between -1 and 1 (it is cosine argument))

relaxxx
  • 6,646
  • 7
  • 34
  • 63

2 Answers2

2

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. 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 (i.e. targetVectorX and targetVectorY are not both equal to zero at the same time) will result in finite pseudoangle values. 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.

Community
  • 1
  • 1
MvG
  • 51,562
  • 13
  • 126
  • 251
2

Check for y being zero as atan2 does; then The quotient x/y will be plenty fine. (assuming I understand you correctly).

Captain Giraffe
  • 13,403
  • 5
  • 35
  • 65