当我希望几件事情相等时,我将它们放在一个数组中并要求 SciPy 最小化该数组的方差。它往往运作良好。
在下面的代码中,我决定(无论好坏)只使用内部点作为变量(称为t
),在计算距离之前插入端点 a、b。另一种方法是使用所有点作为变量,但施加t[0] == a
和的约束t[-1] == b
。
import numpy as np
from scipy import interpolate, optimize
import matplotlib.pyplot as plt
spl = interpolate.CubicSpline(x = [0, 10], y = [0, 10], bc_type=((1, 0), (1, 0)))
def distances_var(t, a, b):
atb = np.concatenate(([a], t, [b])) # added endpoints
y = spl(atb)
dist_squared = np.diff(atb)**2 + np.diff(y)**2
return np.var(dist_squared)
a, b = 0, 10
n = 7 # how many points to put
res = optimize.minimize(distances_var, np.linspace(a, b, n)[1:-1], args=(a, b))
x = np.concatenate(([a], res.x, [b])) # the points we want
xx = np.linspace(a, b, 500) # for plotting the curve
plt.axes().set_aspect('equal')
plt.plot(xx, spl(xx))
plt.plot(x, spl(x), 'ro')
plt.show()
