我有一个问题,类似于那些,我正在发布。我想计算一个三次样条曲线和3条水平线之间的交点。对于所有这些水平线,我都知道y值,并且想找出相交的相应x值。 我希望你能帮助我。我相信对于经验丰富的编码人员来说,这很容易解决!
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(0, 10)
y = np.exp(-x**2.0)
spline = interpolate.interp1d(x, y, kind = "cubic")
xnew = np.arange(0, 9, 0.1)
ynew = spline(xnew)
x1=np.arange(0,10)
y1=1/10*np.ones(10)
x2=np.arange(0,10)
y2=2/10*np.ones(10)
x3=np.arange(0,10)
y3=3/10*np.ones(10)
plt.plot(x,y,'o', xnew, ynew, '-', x1,y1, '-.', x2,y2, '-.', x3,y3, '-.')
plt.show()
for i in range(1,4):
idx = np.argwhere(np.diff(np.sign(spline-y_i))).flatten()
list_idx.append(idx)
print(list_idx)
答案 0 :(得分:1)
您可以使用scipy.interpolate.InterpolatedUnivariateSpline的roots()
函数查找根。因此,首先您必须从函数中减去y-value
并找到根,这将为您提供特定x-value
处的y-value
。
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(0, 10)
y = np.exp(-x**2.0)
spline = interpolate.interp1d(x, y, kind = "cubic")
xnew = np.arange(0, 9, 0.1)
ynew = spline(xnew)
x1=np.arange(0,10)
y1=1*np.ones(10)/10
x2=np.arange(0,10)
y2=2*np.ones(10)/10
x3=np.arange(0,10)
y3=3*np.ones(10)/10
plt.plot(x,y,'o', xnew, ynew, '-', x1,y1, '-.', x2,y2, '-.', x3,y3, '-.')
plt.show()
y_val = 0.2
func = np.array(y) - y_val
sub_funct = interpolate.InterpolatedUnivariateSpline(x, func) # to find the roots we need to substract y_val from the function
root = sub_funct.roots() # find roots here
print(root)
当x
为时,将打印y_val=0.2
值,
[1.36192179]
编辑
您可以按如下所示绘制输出图形。
plt.arrow(root, y_val, 0, -y_val, head_width=0.2, head_length=0.06)