Another service from Omega

Distance from a Point to a Line


*****

Consider a line in 3D with position vector "a" and direction vector "v" and let "p" be the position vector of an arbitrary point in 3D.

We want to compute the distance from the point "p" to the line. Let us call "theta" the angle between "v" and "p-a". The following picture illustrates the situation,

picture a picture here

Thus, the formula for the distance is given by,

| (p-a) x v | / |v|

i.e. the length of the crossprod between the vectors (p-a) and v divided by the length of the vector v. Let us define the "len" function as a procedure and write the formula for the distance in terms of it.

> len := proc(vec) sqrt(innerprod(vec,vec)); end;

Let's try it,

> len([1,1,1]);

                                       1/2
                                      3

> len([x,y,z]);
                                 2    2    2 1/2
                               (x  + y  + z )


It works! Now let's write the formula for arbitrary vectors a,p and v.

> a := vector(3): p := vector(3): v := vector(3):
> dist := len( crossprod(p-a,v) ) / len(v);

               2     2       2     2   
  dist := (v[3]  p[2]  + v[3]  a[2]  +  "a lot more... "


Now let's try it with numbers. First consider a case where the answer is obvious so that we can check wether this thing is working or not.

> a := vector([0,0,0]): p:=vector([0,1,0]): v:=vector([1,0,0]):
> dist;

                                       1


Good. Perhaps we should pack it all for posterity into a "proc".

> d2line := proc(p,a,v) local lc,lv; lv := sqrt(innerprod(v,v)); lc := crossprod(p-a,v); lc := sqrt(innerprod(lc,lc)); lc/lv; end;

d2line := proc(p,a,v)
          local lc,lv;
              lv := sqrt(innerprod(v,v));
              lc := crossprod(p-a,v);
              lc := sqrt(innerprod(lc,lc));
              lc/lv
          end


Before we go ahead to test it, some comments. Notice the use of the "local" variables "lc" and "lv". This means that the names "lc" and "lv" will not overwrite your own definitions with this names outside the "proc", they are "local" to the "proc". Then notice that we re-wrote the "len" program for computing lengths. This is so that we can make "d2line" independent of other procs that would need to be defined.... and finally, notice the use of the "lc" defined in terms of the previous value of "lc". As usual the last thing computed gets returned as the result of the proc. OK back to the test....

> d2line(p,a,v);

                                       1


all wright just as before. One more,

> d2line([-1,1,1],[0,0,0],v);

                                       1/2
                                      2


Hey, I like this!

Homework Problem

Inspired by the above, write the procedure "d2plane".


Link to the commands in this file
Carlos Rodriguez <carlos@math.albany.edu>
Last modified: Wed Oct 23 13:16:17 EDT 1996