本文實例講述了Python實現(xiàn)的擬合二元一次函數(shù)功能。分享給大家供大家參考,具體如下:
背景:
使用scipy擬合一元二次函數(shù)。
參考:
HYRY Studio-《用Python做科學計算》
代碼:
# -*- coding:utf-8 -*-#! python3import numpy as npfrom scipy.optimize import leastsqimport pylab as pldef func(x,p): """ 數(shù)組擬合函數(shù) """ A,k,theta = p return A*(x-k)**2+thetadef residuals(p,y,x): """ 殘差 """ return y-func(x,p)x = np.linspace(0,2,100)A,k,theta = 10.,1,2. #真實數(shù)據(jù)參數(shù)y0 = func(x,[A,k,theta]) #真實數(shù)據(jù)y1 = y0 + 2 * np.random.randn(len(x)) #加入噪聲序列p0 = [7.,0.2,1.]plsq = leastsq(residuals,p0,args = (y1,x))print("真實參數(shù):",[A,k,theta])print("擬合參數(shù):",plsq[0]) #試驗數(shù)據(jù)擬合后的參數(shù)pl.plot(x,y0,label = "real")pl.plot(x,y1,label = "real+noise")pl.plot(x,func(x,plsq[0]),label = "fitting")pl.legend()pl.show()結果:
(貌似這里的求解方法用了智能算法,因為每次的結果都有細小差異。具體資料沒見到,以后有精力再找)
真實參數(shù): [10.0, 1, 2.0]
擬合參數(shù): [ 10.83391995 0.98950039 1.63356065]

PS:這里再為大家推薦兩款相似的在線工具供大家參考:
在線多項式曲線及曲線函數(shù)擬合工具:
http://tools.jb51.net/jisuanqi/create_fun
在線繪制多項式/函數(shù)曲線圖形工具:
http://tools.jb51.net/jisuanqi/fun_draw
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數(shù)學運算技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答