Is there a function in Mathematica that gives me the length of the shortest distance from a given point to a given line?
Yes, RegionDistance:
RegionDistance[InfiniteLine[{0, 0}, {1, 1}], {5, 3}]
> Sqrt[2]
Thanks. It works nicely.
I found in the meantime also the following approach on http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html:
Also this turns out to work quite well, but probably uses a bit more evaluation time:
The distance between the line ax+by+c = 0 and point (u,v) can be shown to be Abs[(au+bv+c)] / Sqrt[a^2 +b^2].
Taking the same line and point as Kuba did, one gets here
a = -1; b = 1; c = 0; u = 5; v = 3;
Abs[(au + bv + c)]/Sqrt[a^2 + b^2]
Sqrt[2]
I seem to find that RegionDistance[] gives odd results, and does not give the same results as equation 14 from http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html:
ln1 = {-3700,-690}; ln2={-3500,765}; pnt={0,0};
regionDistance = RegionDistance[InfiniteLine[ ln1,ln2],pnt]//N
equation14 = Abs[(ln1[[1]]-ln2[[1]])(ln1[[2]]-pnt[[2]])-(ln2[[1]]-pnt[[1]])(ln1[[2]]-ln2[[2]])] / (Sqrt[(ln1[[1]]-ln2[[1]])^2+(ln1[[2]]-ln2[[2]])^2]) //N
I get regionDistance = 1464.15 while the correct answer is equation14 = 3373.43
Your construction of the infinite line is not giving what you expect (check documentation).
Note curly braces in the InfiniteLine below.
In[15]:= ln1 = {-3700, -690}; ln2 = {-3500, 765}; pnt = {0, 0};
regionDistance = RegionDistance[InfiniteLine[{ln1, ln2}], pnt] // N
(* Out[16]= 3571.57 *)
Excellent, thanks. I have no idea how I missed this in the documentation.
Having failed to notice it myself on first glance, I have a good idea of how easy that is to miss. A plot showed me I was not looking at the line I expected to see.
Is there a functionā¦?, may be, but certainly there is a general formula (even valid in R^n). I really appreciate that āRegionDistanceā-stuff, but I prefer an old fashioned understandable way. The line is given by two points v[x] and v[y] and can be written for all t as
g1 = v[x] (1 - t) + v[y] t
Then the square of the distance of any point on the line to a point v[p] is given by
e1 = Distribute[(v[p] - g1).(v[p] - g1)]
We can rewrite this
e2 = e1 /. Dot[Times[x_., v[u_]], Times[y_., v[w_]]] -> x y (v[u].v[w])
e3 = e2 // Expand
Now we can ask for that t yielding the point giving the shortest distance to g1
e4 = D[e3, t] == 0
sol = ((Solve[e4, t] // FullSimplify) /. {v[y].v[x] -> v[x].v[y],v[u_].v[p] -> v[p].v[u]})[[1, 1]]
and this gives for the square of the distance asked for
e5 = (e3 /. sol) // FullSimplify
For your example
e5 /. {v[x] -> {-3700, -690}, v[y] -> {-3500, 765}, v[p] -> {0, 0}};
Sqrt[%] // N
(* 3571.57 *)