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
The black line is the distance I want to calculate
my expectations are: (0.008438554274975979, 0.0085878435595034274819)
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.
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”.
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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With