**Shortest distance between 2 lines drawn in 3D**
R1(t) = (x1(t), y1(t), z1(t)) // t is the independent variable for line 1
R2(s) = (x2(s), y2(s), z2(s)) // s is the independent variable for line 2
D = R1(t) - R2(s) // distance between anywhere on the 2 different lines
We first need to find, for a given point on line 1 (ie at position t), where the shortest distance from this point across to line 2 occurs.
So we start by finding the square of the length of the vector D (ie its dot product (denoted by D.D); this just gives us a nice positive equation to work with). We then find where the derivative of this dot product with respect to s is equal to 0, while also making sure that we are dealing with a minima and not a maxima. From this, we will find the function s(t) (see below):
∂[D.D]/∂s = 0 [1] // derivative of the dot product
∂^2[D.D]/∂s^2 > 0 // ie the double derivative must be positive to ensure that it's a minima
*Note: as there were 2 independent variable in equation D, we needed to use the partial derivative.
Now solve equation [1] to find s(t) // s as a function of t.
What equation s(t) tells us, is that for a given point t (on line 1), the shortest distance to line 2 can be found at point s (on line 2).
So, now all we need to do is find which value of t (on line 1) will give us the overall shortest distance (ie when comparing all the shortest distances already found for the different values of t).
First we re-write equation D using function s(t) (which was found from equation [1] above:
D = R1(t) - R2(s(t)) [2] // now equation D is entirely written with respect to the single independent variable t
And similarly (as we did before):
d[D.D]/dt = 0 [3] // derivative of the dot product (calculated using equation [2])
d^2[D.D]/dt^2 > 0 // ie the double derivative must be positive to ensure that it's a minima
Solving equation [3] to find t, we now have a value (point t on line 1), where the overall shortest line occurs.
Substituting this value of t into equation [2] and finding the length of this vector (ie the square root of its dot product), one should arrive at the value for "the shortest distance between 2 lines drawn in 3D".
I think this approach should also work for n-dimensions (which we would clearly need).