所以,据我了解,你有 3 个点需要拟合抛物线。
通常,最简单的方法是使用numpy.polyfit http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html,但如果您真的担心速度,并且您正好拟合三个点,则使用最小二乘拟合就没有意义。
相反,我们有一个偶数确定的系统(将抛物线拟合到 3 个 x,y 点),并且我们可以通过简单的线性代数得到精确的解。
所以,总而言之,您可能会做这样的事情(大部分是绘制数据):
import numpy as np
import matplotlib.pyplot as plt
def main():
# Generate some random data
x = np.linspace(0, 10, 100)
y = np.cumsum(np.random.random(100) - 0.5)
# Just selecting these arbitrarly
left_idx, right_idx = 20, 50
# Using the mininum y-value within the arbitrary range
min_idx = np.argmin(y[left_idx:right_idx]) + left_idx
# Replace the data within the range with a fitted parabola
new_y = replace_data(x, y, left_idx, right_idx, min_idx)
# Plot the data
fig = plt.figure()
indicies = [left_idx, min_idx, right_idx]
ax1 = fig.add_subplot(2, 1, 1)
ax1.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
ax1.plot(x, y)
ax1.plot(x[indicies], y[indicies], 'ro')
ax2 = fig.add_subplot(2, 1, 2)
ax2.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
ax2.plot(x,new_y)
ax2.plot(x[indicies], y[indicies], 'ro')
plt.show()
def fit_parabola(x, y):
"""Fits the equation "y = ax^2 + bx + c" given exactly 3 points as two
lists or arrays of x & y coordinates"""
A = np.zeros((3,3), dtype=np.float)
A[:,0] = x**2
A[:,1] = x
A[:,2] = 1
a, b, c = np.linalg.solve(A, y)
return a, b, c
def replace_data(x, y, left_idx, right_idx, min_idx):
"""Replace the section of "y" between the indicies "left_idx" and
"right_idx" with a parabola fitted to the three x,y points represented
by "left_idx", "min_idx", and "right_idx"."""
x_fit = x[[left_idx, min_idx, right_idx]]
y_fit = y[[left_idx, min_idx, right_idx]]
a, b, c = fit_parabola(x_fit, y_fit)
new_x = x[left_idx:right_idx]
new_y = a * new_x**2 + b * new_x + c
y = y.copy() # Remove this if you want to modify y in-place
y[left_idx:right_idx] = new_y
return y
if __name__ == '__main__':
main()
希望有点帮助...