I am trying to find the minimum distance from a point (x0,y0,z0) to a line joined by (x1,y1,z1) and (x2,y2,z2) using numpy or anything in python. Unfortunately, all i can find on the net is related to 2d spaces and i am fairly new to python. Any help will be appreciated. Thanks in advance!
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
This duplicates @Hans Musgrave solution, but imagine we know nothing of 'standard calculus tricks' that 'work fine' and also very bad at linear algebra.
All we know is:
(lists are not friends with code blocks)
You should not use this method for real calculations, because it uses approximations wher eyou have a closed form solution, but maybe it helpful to reveal some logic begind the neighbouring answer.
StackOverflow doesn't support Latex, so I'm going to gloss over some of the math. One solution comes from the idea that if your line spans the points
p
andq
, then every point on that line can be represented ast*(p-q)+q
for some real-valuedt
. You then want to minimize the distance between your given pointr
and any point on that line, and distance is conveniently a function of the single variablet
, so standard calculus tricks work fine. Consider the following example, which calculates the minimum distance betweenr
and the line spanned byp
andq
. By hand, we know the answer should be1
.This works fine in any number of dimensions, including 2, 3, and a billion. The only real constraint is that
p
andq
have to be distinct points so that there is a unique line between them.I broke the code down in the above example in order to show the two distinct steps arising from the way I thought about it mathematically (finding
t
and then computing the distance). That isn't necessarily the most efficient approach, and it certainly isn't if you want to know the minimum distance for a wide variety of points and the same line -- doubly so if the number of dimensions is small. For a more efficient approach, consider the following:There may well be some simplifications I'm missing or other things that could speed that up, but it should be a good start at least.