tags:

views:

307

answers:

5

I have 2 points, P and Q, on a directed line AB in 3D space. They can be anywhere on the line, i.e. not necessarily between A and B.

Pythagoras gives you the distance, obviously, but how do I calculate the sign of the directed distance from P to Q?

Accepted answer: I was aware of Nick's solution, but I find it ugly because of the test you have to do (check if AB is parallel to any of the axis). So instead I chose Zach's solution; it's short and straightforward. I guess I'm didn't think of it because I'm not familiar enough with vector algebra. Thanks for the replies everybody.

A: 

For each dimension (x,y,z) it will either be increasing, decreasing or constant for A->B. This can be found by doing B-A (xB-xA, yB-yA, zB-zA). For your points calculate the equivalent value for Q-P. If the sign is the same in x (or y or z) as it is for B-A then the direction is the same as AB, otherwise it is different.

You only need to look at 1 of x,y, or z, but if AB is constant in x,y, or z you need to choose another dimension.

Nick Fortescue
A: 

Sounds like you're asking about vectors. I don't know if you've studied them yet, but they're quantities that have both magnitude and direction.

If your two points in space are (p1, p2, p3) and (q1, q2, q3), you can form the vector pointing from P to Q in 3D space like this:

V = (q1-p1)i + (q2 - p2)j + (q3 - p3)*k

where (i, j, k) are vectors of magnitude 1 in the x, y, and z-directions, respectively.

The magnitude (e.g., distance) from P to Q is the square root of the sum of squares of the components.

duffymo
A: 

The points are on the line A-B, and you want the distance from P to Q.

The line is directed from A to B, so you can define an alpha such that:

Point = alpha (B-A) + A

You find the alpha of P and Q, and if the alpha of P is greater than that of Q, the sign is negative.

Gamecat
+5  A: 

Take the dot product of AB and PQ. Positive => same direction, negative => opposite direction.

Zach Scrivena
+2  A: 

Treating the differences Q-P and B-A as vectors AB and PQ , the sign is given by the sign of the dot product of the vectors.

sign( signed_distance ) = sign( PQ · AB )

where

[x,y,z] · [ p,q,r ] = x✕p + y✕q + z✕r

If you normalise the vector AB by dividing it by its magnitude ( the sqrt of the dot product with itself ),

N = AB / | AB |

Then the signed distance along the direction of AB will be

signed_distance = PQ · N

Which means you only need to do the sqrt once if A and B don't change.

Pete Kirkham
+1 - a typical comment from you, Pete. Nice. Even the typesetting looks good.
duffymo