views:

123

answers:

4

I have two 2D vectors, say u and v, defined by cartesian coordinates.

Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vectors are aligned answer should be before.

It seems easy using some trigonometry, but I believe there should be a faster way using coordinates only.

My test case:

def after(u, v):
    """code here"""
  • after((4,2), (6, 1)) : True
  • after((4,2), (3, 3)) : False
  • after((4,2), (2, 1)) : False
  • after((4,2), (3, -3)) : True
  • after((4,2), (-2, -5)) : True
  • after((4,2), (-4, -2)) : False
+10  A: 
def after(u, v):
    # return sign of cross product
    return u[0]*v[1]<u[1]*v[0]

don't know if it's fast, but it is terse

Pete Kirkham
Thanks. It's exactly what I was looking for.
kriss
A: 

General idea: Rotate the x-axis to coincide with v and check that the new y coordinate of u is positive.

Anon
If you work out the math for rotation using this link http://en.wikipedia.org/wiki/Rotation_(mathematics)#Matrix_algebra you recover the method suggested by Pete.
Anon
A: 

So you want to know what side of the line representing vector u the point at the head of vector v lies ? I hit Google (query: point on side of line) for an algorithm; found a ton, this one (read the second post) does it without trigonometry.

High Performance Mark
A: 

If you're going by rotation, you can use simple trigonometry to figure out the rotation.

Remember the three rules from high school trig class? "SOH CAH TOA" ring any bells? This is what they mean:

Given the right triangle:

A *
  | \
  |  \
  |   \
B *----* C

SOH:

The sine of any angle formed by ∆ABC is equal to the opposite side length divided by the length of the hypotenuse. For instance, in order to find the angle formed at point C:

             __
             AB
SIN(∠BCA) = ----
             __
             AC

CAH:

The cosine of any angle formed by ∆ABC is equal to the length of the adjacent side (not the hypotenuse) divided by the length of the hypotenuse. So, for example, to find the angle formed at point C:

             __
             BC
COS(∠BCA) = ----
             __
             AC

TOA:

The tangent of any angle formed by ∆ABC is equal to the length of the opposite side divided by the length of the adjacent side (not the hypotenuse). So, for example, to find the angle formed at point C:

             __
             AB
TAN(∠BCA) = ----
             __
             BC

So, if you can determine any of these measurements, you can determine the rest, provided you think of the right triangle formed by the coordinate and the axes.

amphetamachine