0

我正在从一堆(x,y)采样点拟合参数样条曲线(t)。如何计算与斜率和一个点给出的线的交点?在我的特殊情况下,样条与线相交一次或根本不相交,但不会多次。

这是样条和线的代码......

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate


# Fit spline from points
x = np.array([152, 200, 255, 306, 356, 407, 457, 507, 561, 611, 661, 711, 761, 811, 861])
y = np.array([225, 227, 229, 229, 228, 226, 224, 222, 218, 215, 213, 212, 212, 215, 224])
tck, u = interpolate.splprep((x, y), k=3, s=1)

# Plot it...
u = np.linspace(0, 1, 100)
xy = np.asarray(interpolate.splev(u, tck, der=0))
plt.plot(*xy)


# Line defined by slope and (x, y) point
m = 3
(x, y) = (500, 100)

# Plot it...
x_vals = np.array([400, 700])
y_vals = m * (x_vals - x) + y
plt.plot(x_vals, y_vals)
plt.show()

...看起来像这样: 阴谋

4

1 回答 1

0

添加以下行

from scipy.interpolate import interp1d
spline = interp1d(xy[0], xy[1]) # define function based on spline data points
line = interp1d(x_vals, y_vals) # define function based on line data points

import scipy.optimize as spopt
f = lambda x: spline(x) - line(x) # difference function, its zero marks the intersection
r = spopt.bisect(f, a = max(xy[0][0], x_vals[0]), b = min(xy[0][-1], x_vals[-1])) # find root via bisection

plt.scatter(r, spline(r))
print(r, spline(r))
plt.show()

首先根据其数据为您的样条和直线定义函数。差分函数的根f标记了您的交集。因为只有一个,所以二分法可以很好地找到它。

以某种方式重新使用splev来定义样条曲线的函数可能会更准确,但我会把那个留给你。

于 2020-07-27T15:31:38.897 回答