2015-10-06 69 views
0

的功能,我有一個數據集爲:極小元組

2.699994 -2541.184861 
2.749996 -2541.189717 
2.779995 -2541.190735 
2.789996 -2541.190777 
2.799993 -2541.190668 
2.829992 -2541.189523 
2.858996 -2541.187427 

我知道這適合於多項式例如爲:f(x)=a+b*x+c*x^3

我需要得到函數的最小值。

我搜索了一下,看起來像scipy.optimize是我正在尋找,但無法理解如何提供數據。 請幫忙

回答

1

所以有兩個步驟:首先通過擬合函數找到參數。我爲此使用了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() 

data and fit