Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the distance between two points on lines in python

I have two lines. namely (x1,y1) and (x2,y2). I need to calculate the distance between the points. see my code snippets below

import numpy as np
import plotly.express as px
import plotly.graph_objects as go

x1= np.array([525468.80914272, 525468.70536016])
y1= np.array([175517.80433391, 175517.75493122])

x2= np.array([525468.81174, 525468.71252])
y2= np.array([175517.796305, 175517.74884 ])

Here is the code for the plot:

fig= go.Figure()

fig.add_trace(go.Scatter(x=x1, y=y1, name="point1"))
fig.add_trace(go.Scatter(x=x2, y=y2, name="point2"))

See the figure here

1

The black line is the distance I want to calculate

my expectations are: (0.008438554274975979, 0.0085878435595034274819)

like image 610
I-love-python Avatar asked Jan 27 '21 08:01

I-love-python


People also ask

How do you use the distance function in Python?

dist() method in Python is used to the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension. This method is new in Python version 3.8. Returns: the calculated Euclidean distance between the given points.

How do you find the length of a line in Python?

Using the len() method To calculate the length of a string in Python, you can use the built-in len() method. It takes a string as a parameter and returns an integer as the length of that string. For example len(“educative”) will return 9 because there are 9 characters in “educative”.


2 Answers

You can solve this with math library

import math

distancePointA  = math.sqrt(((x1[0] - x2[0]) ** 2) + ((y1[0] - y2[0]) ** 2))
distancePointB  = math.sqrt(((x1[1] - x2[1]) ** 2) + ((y1[1] - y2[1]) ** 2))
like image 66
frux09 Avatar answered Nov 15 '22 07:11

frux09


The distance here is just the l2 or euclidian norm. You can use numpy for this.

import numpy as np
distance_1 = np.linalg.norm(np.array([x1[0]-x2[0],y1[0]-y2[0]]))
distance_2 = np.linalg.norm(np.array([x1[1]-x2[1],y1[1]-y2[1]]))

print(distance_1,distance_2)

output:

0.008438557910490769 0.009400333483144686

The default norm that np.linalg.norm uses is the euclidian norm. (the distance the black lines represent)

like image 44
joostblack Avatar answered Nov 15 '22 06:11

joostblack