import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'SimHei'
rcParams['axes.unicode_minus'] = False
# 定义原始函数
def func(x,p):
'''
x:表示函数的未知数x。
p:接收tuple,list。表示函数的系数,例如ax+b中的a,b。无默认。
'''
a,k,thera = p
return a*np.sin(2*np.pi*k*x+thera)
# 定义误差
def regula1(p,y,x):
'''
p:接收tuple,list。表示函数的系数,例如ax+b中的a,b。无默认。
x:表示函数的未知数x。
y:表示函数的未知数y。
'''
return y-func(x,p)
x= np.linspace(1,2*np.pi,100)
A,K,Thera = 10,0.34,np.pi/6
y0 = func(x,[A,K,Thera])
np.random.seed(123)
y1 = y0+2*np.random.randn(x.shape[0]) # 为真实值加入噪声
p0 = [7,0.40,0]
# 最小二乘法确定a,k,thera
result1 = optimize.least_squares(regula1,p0,args=[y1,x])
p1,p2,p3 = result1.x # 取出结果
print('最小二乘拟合的结果:\n\
a:%s,\nk:%s,\nthera:%s'%(p1,p2,p3))
最小二乘拟合的结果:
a:10.116135052023576,
k:0.3397272553014279,
thera:0.48219742621350414
print('最小二乘拟合的结果展示:')
plt.figure(figsize=(6,4))
plt.scatter(x,y1,label='噪声数据') # 噪声数据
plt.plot(x,y0,'r-',label='真实曲线') # 真实曲线
plt.plot(x,func(x,[p1,p2,p3]),'b:',label='拟合曲线') # 拟合曲线
plt.legend()
plt.title('含噪声函数拟合')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,7)
plt.show()