views:

88

answers:

4

I want to know how to get an angle of a line A-B from horizontal axis X. Other questions in SO do that only between two lines. I'm aware I can always draw second line A-C and calculate but I'm wondering if there's a faster method.

EDIT: I'm very sure I'm not doing a premature optimization.

A: 

The x-axis is actually a line with equation

y = 0

so you could use the solution you have already.

Charlie Salts
I was looking for faster (less cpu) method if there's any.
VOX
+4  A: 

You can use atan for that.

angle = atan((By-Ay)/(Bx-Ax))
Bart van Heukelom
+1  A: 

If

  1. The angle is small,
  2. you can live with small inaccuracies, and
  3. You can use the angle in radians and not degrees,

then there is a fast solution: Under these conditions, you can assume that tan(a) = a = atan(a), and hence just omit the atan() call.

Frank
thanks for a good point.
VOX
"tan(a) = a = atan(a)" Eh...what?
Bart van Heukelom
@Bart van Heukelom:Yes, as I wrote, this is not exact, but a good approximation for small angles.E. g. tan(0.1) = 0.1003, tan(0.2) = 0.203So for angles in this range, if you do not need absolute precision, you can save some calculation effort.
Frank
Yes, that seems to be true. The inaccuracies already get too large once the angle is larger than about 10 degrees though, and I think that if you're dealing with small angles you'll usually want the highest precision anyway.
Bart van Heukelom
@Bart: As the OP stated that performance with limited resources is very important, I just wanted to make him aware of this optimization possibility which may or may not be a solution for the problem, as he did not state anything about the typical or worst case size of the angles.
Frank
+1  A: 

You could also use arccosine, if your line is in the form [r_x,r_y], where r_x is the change in x and r_y is the change in y.

angle = arccos( r_x/( r_x*r_x + r_y*r_y ) )

It's slightly more opaque, but it's basically the dot product law:

angle = arccos (r . v)

Where r and v are both unit vectors (vectors of length 1). In our case, v is the vector [1,0], and r is

[r_x,r_y] / (r_x^2+r_y^2)

in order to make it a unit vector.

Justin L.