Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-067

Distance from Point to Line 2D

Problem

Compute the distance from point p to the line through points a and b in 2D:

d = |cross(b - a, p - a)| / ||b - a||_2

If a == b, return the point distance ||p - a||_2.

Hint

The cross product gives twice the triangle area; divide by the base length.

Test cases

case 1
in: [[2,3],[0,0],[4,0]]
expected: 3
case 2
in: [[1,0],[0,0],[1,1]]
expected: 0.7071067811865475
case 3
in: [[4,5],[1,1],[1,1]]
expected: 5
case 4
in: [[0,0],[0,0],[3,4]]
expected: 0
Starter codePython
def point_line_distance(p, a, b):
    # Your code here
    pass

4 test cases · run your code against them in the editor