Skip to content
Advertisement

How to find nearest point in segment in a 3d space

I am solving an algorithmic problem which sounds like this:

Given a three-dimensional space and segments in it. Find the point with minimal distance to all of the segments. Example input: in the first line N – the number of segments, in the N next lines given the begin and the end of each segment: x1 y1 z1 x2 y2 z2

I know what kind of a given problem it is (a geometrical median) and I already know how to find the minimal distance between point and segment (Cartesian distance and a nice code provided here), but what I need – is a point (x, y, z) on a segment to which I found the distance. I need to know it to approximate my result.

Here is the code I have

JavaScript

For example distance from [0, 0, 0] point to segment is known and we can say that the closest point of the segment to us is [1, 1, 1]. But how do we find the nearest point in other cases?

Advertisement

Answer

From your last paragraph I understand you need to find a point in a segment that is closest to another point.

This function returns both the closest point and the distance:

JavaScript

It is also faster than the code you have.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement