Kinshuk
Kinshuk

Reputation: 3

Python: Calculate distance of point from N Dimensional line

I have a bunch of 4D points, and I'm looking to get their perpendicular distance from the line w=x=y=z (assuming w,x,y,z to be the 4D axes). It seems like there should be an easy way to do this in python, but I can't seem to figure it out.

Aside: This is basically a 4D scatter plot, and I'm trying to see how far each point is from the ideal scenario (w=x=y=z). Is there a mathematical term for this metric?

Upvotes: 0

Views: 2264

Answers (2)

Cobry
Cobry

Reputation: 4548

This is an implementation of euclidian distance that works for any number of dimensions

def distance_to_line(line, pts, l0=None, p0=None):
    """
    line defined between l0 and line 
    points defined between p0 and pts
    """
    # line origin other than (0,0,0,..)
    if l0 is not None:
        line = line-l0
    # points origin other than (0,0,0,..)
    if p0 is not None:
        pts = pts-p0
    dp = np.dot(pts,line)
    pp = dp/np.linalg.norm(line)
    pn = np.linalg.norm(pts, axis=1)
    return np.sqrt(pn**2 - pp**2)



distance_to_line(l0=np.transpose((0,0,0,0,0)),
                 line=np.transpose((1,1,0,0,0)),
                 pts=np.array([(2,0,0,0,1),
                               (1,1,0,0,1),
                               (0,1,0,0,1),
                               (1,2,0,0,1)]))

>>> array([ 1.73205081,  1.        ,  1.22474487,  1.22474487])

Upvotes: 0

MBo
MBo

Reputation: 80137

Any line has parametric equation with some base point and unit direction vector. Here P0=(0,0,0,0) and u=(1/2, 1/2, 1/2, 1/2).
Vector from base point to every point P is equal to their coordinates, and distance from P to the line is:

 D = (P - (P.dot.u) * u).length

enter image description here

Scalar product approach works for any number of dimensions.

Upvotes: 2

Related Questions