寻找计算两条曲线之间距离的解决方案

时间:2021-02-12 21:50:36

标签: python dataframe numpy

我需要计算两条曲线之间的最小和最大距离(正常) 即来自一条曲线的点在另一条曲线上垂直。 到目前为止我做了什么:

from sympy import *
from pandas import DataFrame
init_printing(use_unicode=False, wrap_line=False)
x = Symbol('x')

F=x+1 #first curve
G=x**2 #second curve
#on the interval [1:5]

My_list =np.transpose( [np.arange(1, 5, 1)] )
df = DataFrame(My_list, columns=['x']) # x array to data frame
df['yF'] = df['x']+1  #adding first function
df['yG'] = df['x']** 2 #adding second function
df['r']= abs(df['yF']-df['yG']) #calculating distance
df.describe()  #to look min-max

问题是:距离并不是真正垂直于曲线...解决方案看起来不是最佳的。

1 个答案:

答案 0 :(得分:0)

您没有找到垂直距离。您正在寻找具有固定 x 值的 y 值的最小值。您的步骤需要如下所示:

  1. 找到其中一条曲线的所有垂直线。
  2. 在另一条曲线上找到相应的交点。
  3. 计算距离。

请注意,此方法不是可交换的,f 到 g 的垂直距离可能与 g 到 f 的垂直距离不同。这是因为你不能保证如果一条直线垂直于曲线 f,它也一定垂直于曲线 g。

一些数学:

  1. F 的导数是 1
  2. G 的导数是 2*X
  3. Y=X+1 在点 x 的垂线是 Y=-X+(2*x+1)。
  4. Y=X**2 在点 x 的垂线是 Y=-1/(2*x)*X+(x**2+0.5)
  5. 交叉点可能有多个解决方案

我会用 numpy 显示。

import numpy as np

#Functions, d is the derivative
F  = lambda x : x+1  
dF = lambda x : np.ones(x.shape)
G  = lambda x : x**2
dG = lambda x : 2*x

#Domain
X  = np.arange(1,5,1)

#We calculate the distance from G to F
P_m = -1/dG(X)                                  #Perpendicular slopes
P_b = X**2+0.5                                  #The y-intercept
C   = (2*X**3-X)/(2*X+1)                        #The x-coor of the intersection
D   = np.sqrt((X-C)**2+((P_m*X+P_b)-F(C))**2)   #Distance
print(D.min())

#Now the other way (this way has two intersection points). 
P_m = -1/dF(X)                                  #The perpendicular slopes 
P_b = 2*X+1                                     #The y-intercepts 
C1  = 0.5*(-P_m+np.sqrt(P_m**2+4*P_b))          #First solution
C2  = 0.5*(-P_m-np.sqrt(P_m**2+4*P_b))          #Second solution 
D1  = np.sqrt((X-C1)**2+((P_m*X+P_b)-G(C1))**2) #Euclidian distance to first solution
D2  = np.sqrt((X-C2)**2+((P_m*X+P_b)-G(C2))**2) #Euclidian distance to second solution
D   = np.concatenate([D1,D2])                   #Distance
print(D.min())                                  #Minimum distance
相关问题