# Distance from Point to Line in 3D

So I have the following 3D co-ordinates that marks the start and end point of a line:

$\left(\begin{array}{c}1\\ 1\\1\end{array}\right)$ $\left(\begin{array}{c}-1\\ -1\\1\end{array}\right)$

The point from where I need to find the distance is given by:

$\left(\begin{array}{c}\sqrt{1/8}\\ \sqrt{1/8}\\\sqrt{3/4}\end{array}\right)$

Is it possible to do it using vector algebra? I am actually writing a computer program where this needs to be implemented, what will be the simplest formula to do it?

Thanks and regards.

• Are you looking for the Euclidean distance from your third point to the nearest point on the line segment? Are you allowed to extend the line segment beyond the end points? Nov 13, 2016 at 22:12
• @Henry I think I am looking at Euclidean distance yes. Are you allowed to extend the line segment beyond the end points? - I am not sure what this means, but the only data I have is the one cited above. If that's sufficient for the computation, then it's fine by the work. Nov 13, 2016 at 22:14
• calculate the projection $p(C)$ of point $C$ on the line through your 2 points $A$ and $B$, check the relative position of that projection $p(C)$ on the line to the 2 points $A$ and $B$: is it in the convex? if it is is not in the convex, then replace $p(C)$ by its nearest neighbor (either $A$ or $B$). calculate the distance of $C$ and $p(C)$.
– Max
Nov 13, 2016 at 22:15
• @Max any simple programmable formula? I am sorry, I am really not a math guy! Nov 13, 2016 at 22:16
• this is basic linear algebra. use google/wiki, you will find projection formulae.
– Max
Nov 13, 2016 at 22:17

You can express any point on the line as $$v = a + \lambda (b-a)$$

Now, the point which will have smallest distance will be foot of perpendicular from given point to the line. Hence, we find $\lambda$ for which $$(v-p).(b-a)=0$$ $$\implies ((a-p)+\lambda(b-a)).(b-a)=0$$ $$\implies \lambda = \frac{(p-a).(b-a)}{|b-a|^2}$$

Hence, we can obtain $v$, and to find distance, we simply do $$d=|v-p|$$

This should be easy enough to implement in code

• So $p$ is the given point and $(p−a).(b−a)$ is the dot product ? Also, how do I calculate $v$ based on the co-ordinates above in the question? Nov 13, 2016 at 22:31
• Yeah, p is the given point. So we would calculate $v$ by first finding $\lambda$ , and then plugging that value into $v=a + \lambda(b-a)$ Nov 14, 2016 at 6:13
• Why doesn't this solution give an exact answer? I made an example in CAD where a = (0, 0, 0) b = (1, 1, 0) p = 1.2, -0.2, 0) which gives d = 1. But this calculation gives 0.989949...? Is it possible to get an exact answer? Jan 21, 2019 at 16:07

Hint

The parametric equations of your line are

$x=1+2t\;,\,y=1+2t\;,\;z=1$

we look for $t$ such that

$2(\frac{ 1 }{\sqrt{8}}-1-2t)$ $+2(\frac{1 }{\sqrt{8}}-1-2t)=0$

the distance is $$d=1-\frac{\sqrt{3}}{2}.$$