首页 > 编程 > Python > 正文

Python实现的拟合二元一次函数功能示例【基于scipy模块】

2020-02-23 00:07:48
字体:
来源:转载
供稿:网友

本文实例讲述了Python实现的拟合二元一次函数功能。分享给大家供大家参考,具体如下:

背景:

使用scipy拟合一元二次函数。

参考:

HYRY Studio-《用Python做科学计算》

代码:

# -*- coding:utf-8 -*-#! python3import numpy as npfrom scipy.optimize import leastsqimport pylab as pldef func(x,p):  """  数组拟合函数  """  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. #真实数据参数y0 = func(x,[A,k,theta]) #真实数据y1 = y0 + 2 * np.random.randn(len(x)) #加入噪声序列p0 = [7.,0.2,1.]plsq = leastsq(residuals,p0,args = (y1,x))print("真实参数:",[A,k,theta])print("拟合参数:",plsq[0]) #试验数据拟合后的参数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()

结果:

(貌似这里的求解方法用了智能算法,因为每次的结果都有细小差异。具体资料没见到,以后有精力再找)

真实参数: [10.0, 1, 2.0]
拟合参数: [ 10.83391995   0.98950039   1.63356065]

PS:这里再为大家推荐两款相似的在线工具供大家参考:

在线多项式曲线及曲线函数拟合工具:
http://tools.jb51.net/jisuanqi/create_fun

在线绘制多项式/函数曲线图形工具:
http://tools.jb51.net/jisuanqi/fun_draw

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表