【问题标题】:How to calculate the distance between two points on lines in python如何计算python中线上两点之间的距离
【发布时间】:2021-05-01 01:27:23
【问题描述】:

我有两条线。即(x1,y1)(x2,y2)。我需要计算点之间的距离。请参阅下面的代码 sn-ps

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)

【问题讨论】:

标签: python python-3.x dataframe numpy math


【解决方案1】:

您可以使用基于勾股定理的距离公式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

【讨论】:

    【解决方案2】:

    这里你可以使用毕达哥拉斯定理计算距离,这里我定义了两种方法

    • 你可以通过a=x1-x2b=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 方法hypot 的方程式
    import 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)
    
    

    这些都是你可以使用它们中的任何一种的方法,但最终你会得到距离

    【讨论】:

    • 我收到错误 - TypeError: only size-1 arrays can be convert to Python scalars
    • @pandas-py 我已更改请检查让我知道在哪种情况下您会收到此错误
    • 好吧,这是因为数学不适用于向量,所以我改用 numpy。看起来不错,但我没有得到期望,即 distance_a 为 0.008438557910490769
    【解决方案3】:

    这里的距离只是 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 使用的默认范数是欧几里得范数。 (黑线代表的距离)

    【讨论】:

    • 哎呀,我的错。我忘了括号。现在应该修好了。
    【解决方案4】:

    您可以使用 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))
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2010-10-30
      • 2021-04-26
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多