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,
Thus, the formula for the distance is given by,
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,|
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 p + v a + "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]):
|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....|
|all wright just as before. One more,|
Hey, I like this!
Homework ProblemInspired by the above, write the procedure "d2plane".