The distance between a point and a line (two points)

I use Python + Numpy (maybe I also use Scipy) and have three 2D points

(P1, P2, P3); 

I am trying to get the distance from P3 perpendicular to the line drawn between P1 and P2. Let P1=(x1,y1), P2=(x2,y2)andP3=(x3,y3)

In vector notation, that would be pretty simple, but I'm pretty new to python / numpy and can't get anythng that works (or even close).

Any advice appreciated, thanks!

+10
source share
6 answers

Try using the norm function from numpy.linalg

d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1)
+18
source

np.cross z- . norm , , p3 - , .

d=np.cross(p2-p1,p3-p1)/norm(p2-p1)

p3 .

+5

, , , :

import numpy as np
p1=np.array([0,0])
p2=np.array([10,10])
p3=np.array([5,7])
d=np.cross(p2-p1,p3-p1)/np.linalg.norm(p2-p1)
+3
abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / np.sqrt(np.square(x2-x1) + np.square(y2-y1))

, , .

+1

, , https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line Python:

def distance(point,coef):
    return abs((coef[0]*point[0])-point[1]+coef[1])/math.sqrt((coef[0]*coef[0])+1)

Coef -

+1

, https://www.geeksforgeeks.org:

import math 

# Function to find distance 
def shortest_distance(x1, y1, a, b, c):    
    d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) 
    print("Perpendicular distance is", d)

A, B, C, x y.

import numpy as np
closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]

:

shortest_dis = shortest_distance(x, y, A, B, C)

:

import math
import numpy as np

def shortest_distance(x1, y1, a, b, c):    
    d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) 
    print("Perpendicular distance is", d)

closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]
shortest_dis = shortest_distance(x, y, A, B, C)
#print(shortest_dis)

, , -

0

Source: https://habr.com/ru/post/1656634/


All Articles