How to check if 3d float point lies on a line within error?

Viewed 27

The line is not a line segment, but should extend to infinity. I tried using this guys answer but I just got nan's because I was dividing by 0. Preferably I want something quick and easy with dot and cross products and such.

x = np.array([-1,-1,-1])
y = np.array([4,4,4])
a = np.array([2,2,2])

epsilon = 0.0001

#algorithm

print((x[2] - x[0]) / (x[1] - x[0]))
print((y[2] - y[0]) / (y[1] - y[0]))
print((a[2] - a[0]) / (a[1] - a[0]))

Ouput:

nan
nan
nan
1 Answers

Here is one possibility, depending on the application the code can be simplified, but I preferred to give a solution with a clear interpretation rather than a clear code.


def colinear(p1, p2, p3, rtol=1e-5):
    '''
    Test colinearity making sure that sin(angle) < rtol
    '''
    # twice the area of the triangle (p1, p2, p3)
    A = np.linalg.norm(np.cross(p2 - p1, p3 - p1))
    # length of two sides meeting the vertice p1
    a = np.linalg.norm(p2 - p1)
    b = np.linalg.norm(p3 - p1)
    c = np.linalg.norm(p2 - p3)
    
    # pick the two largest sides
    _, a, b = sorted([a,b,c])
    # the angle at the vertice where those points meet
    # will be A / (a * b)
    return A < rtol * a * b

x = np.array([-1,-1,-1])
y = np.array([4,4,4])
a = np.array([2,2,2])
assert colinear(x, y, a)
Related