2015-10-06 59 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