所以有兩個步驟:首先通過擬合函數找到參數。我爲此使用了curve_fit。然後最小化功能。我使用最小化,但這也可以通過分析來完成。
import scipy as sp
import scipy.optimize
import matplotlib.pyplot as plt
%matplotlib inline
# data
xdata = sp.array([2.699994, 2.749996, 2.779995, 2.789996, 2.799993, 2.829992, 2.858996])
ydata = sp.array([-2541.184861, -2541.189717, -2541.190735, -2541.190777, -2541.190668, -2541.189523, -2541.187427])
# function to fit
def f(x, a, b, c):
return a + b*x + c*x**3
# fit the parameters a, b, c
popt, pcov = sp.optimize.curve_fit(f, xdata, ydata)
print('Parameters a, b, c are: {0}'.format(popt))
# minimize the function (could also be done analytically)
res = sp.optimize.minimize(lambda x: f(x, *popt), 2.8)
print('Function is minimized for {0}.'.format(float(res['x'])))
# plot data, fitted function and minimum
# function
x = sp.linspace(2.65, 2.9, 100)
y = f(x, *popt)
plt.plot(x, y)
# data
plt.scatter(xdata, ydata)
# minimum
plt.scatter(res['x'], f(res['x'], *popt), color = 'red', s = 80)
plt.show()