我有两行。即 (x1,y1)
和 (x2,y2)
。我需要计算点之间的距离。在下面查看我的代码片段
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 ])
这是情节的代码:
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"))
看这里的图
黑线是我要计算的距离
我的期望是:(0.008438554274975979, 0.0085878435595034274819)
答案 0 :(得分:3)
您可以使用 math
库解决此问题
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))
答案 1 :(得分:2)
这里的距离只是 l2 或欧几里得范数。您可以为此使用 numpy。
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)
输出:
0.008438557910490769 0.009400333483144686
np.linalg.norm 使用的默认范数是欧几里得范数。 (黑线代表的距离)
答案 2 :(得分:2)
您可以使用基于勾股定理的距离公式:AB=√((xA-xB)²+(yA-yB)²)
其中 (xA, yA)
, (xB, yB)
是两点 A, B 的坐标。
应用于您的问题:
import math
distance_1 = math.sqrt(((x1[0] - x2[0]) ** 2) + ((y1[0] - y2[0]) ** 2))
distance_2 = math.sqrt(((x1[1] - x2[1]) ** 2) + ((y1[1] - y2[1]) ** 2))
print(distance_1, distance_2)
输出:
0.008438557910490769 0.009400333483144686
答案 3 :(得分:1)
这里你可以使用勾股定理来计算距离,这里我定义了两种方法
a=x1-x2
和 b=y1-y2
获得一个距离为 c=?
在公式中传递值,如 import math
a=x1-x2
b=y1-y2
c=abs(math.sqrt((a** 2) + (b ** 2)))
这里是你的情况
import math
a1 = x1[0] - x2[0]
a2 = x1[1] - x2[1]
b1 = y1[0] - y2[0]
b2 = y1[1] - y2[1]
distance_a = abs(math.sqrt((a1** 2) + (b1** 2)))
distance_b = abs(math.sqrt((a2** 2) + (b2 ** 2)))
hypot
方法,它给出相同的答案,就像见 hypot
方法 hypotimport math
a1 = x1[0] - x2[0]
a2 = x1[1] - x2[1]
b1 = y1[0] - y2[0]
b2 = y1[1] - y2[1]
distance_a = math.hypot(a1,b1)
distance_b = math.hypot(a2,b2)
这些都是你可以使用其中任何一种的方式,但最终你会得到距离