赞
踩
本文实例讲述了Python实现的拟合二元一次函数功能。分享给大家供大家参考,具体如下:
背景:
使用scipy拟合一元二次函数。
参考:
HYRY Studio-《用Python做科学计算》
代码:
# -*- coding:utf-8 -*-
#! python3
import numpy as np
from scipy.optimize import leastsq
import pylab as pl
def func(x,p):
"""
数组拟合函数
"""
A,k,theta = p
return A*(x-k)**2+theta
def 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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。