import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x = np.arange(1, 17, 1)
y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])
#多项式拟合
def poly_fit():
z = np.polyfit(x, y, 3)#用3次多项式拟合
p = np.poly1d(z)
print(p) #在屏幕上打印拟合多项式
x2=np.arange(1,20)
y_fit=p(x2)#也可以使用yvals=np.polyval(z,x)
plt.plot(x, y, '*',label='original values')
plt.plot(x2, y_fit, 'r',label='polyfit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4)#指定legend的位置,loc=4,表示图标位于第四象限
plt.title('poly_fit')
plt.show()
# plt.savefig('poly.png')
#使用非线性最小二乘法拟合,a*e(b/x)
def aebx_fit():
def func(x, a, b):
return a * np.exp(b / x)
popt, pcov = curve_fit(func, x, y)
a, b = popt # popt里面是拟合系数,读者可以自己help其用法
x2=np.arange(1,20)
yvals = func(x2, a, b)
plt.plot(x, y, '*', label='original values')
plt.plot(x2, yvals, 'r', label='curve_fit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4) # 指定legend的位置,loc=4,表示图标位于第四象限
plt.title('a*e(b/x)')
plt.show()
# plt.savefig('aebx.png')
#a*e(b/x)+c拟合
def aebxc_fit():
def func(x, a, b,c):
return a * np.exp(b / x)+c
popt, pcov = curve_fit(func, x, y)
a,b,c=popt# popt里面是拟合系数
x2=np.arange(1,30)
yvals = func(x2, a, b,c)
plt.plot(x, y, '*', label='original values')
plt.plot(x2, yvals, 'r', label='curve_fit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4) # 指定legend的位置,loc=4,表示图标位于第四象限
plt.title('a*e(b/x)+c')
plt.show()
# plt.savefig('aebxc.png')
#aX的b次方拟合
def axb_fit():
def func(x, a, b):
return a * pow(x, b)
popt, pcov = curve_fit(func, x, y)
a,b = popt # popt里面是拟合系数,读者可以自己help其用法
x2 = np.arange(1, 20)
yvals = func(x2, a, b)
plt.plot(x, y, '*', label='original values')
plt.plot(x2, yvals, 'r', label='curve_fit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4) # 指定legend的位置,loc=4,表示图标位于第四象限
plt.title('axb')
plt.show()
#plt.savefig('axb.png')
if __name__ == '__main__':
poly_fit()
aebx_fit()
aebxc_fit()
axb_fit()