使用python scipy进行曲线拟合

应用背景:根据某地每月的平均温度[17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18],拟合温度函数,目标函数是y=asin(xpi/6+b)+c。

下面是具体的实现代码:

# import some useful packages
import numpy as np
import matplotlib.pyplot as plt   # 绘图函数
from scipy import optimize        # 优化函数

# construct the input data
x1=np.arange(1,13,1)
x2=np.arange(1,13,0.1)
y1=np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18 ])

# define the target function
def func(x,a,b,c):
    return a*np.sin(x*np.pi/6+b)+c

# run the optimization
fita,fitb=optimize.curve_fit(func,x1,y1,[1,1,1])

# print the optimized parameters
print(fita)

# plot the figure
plt.plot(x1,y1)
plt.plot(x2,func(x2,fita[0],fata[1],fita[2]))
plt.show()

运行上面的程序,可以求出a b c的值为[ 10.93254952 -1.9496096 26.75]。

绘制的曲线如下图所示:

使用python scipy进行曲线拟合

Refer: http://www.cnblogs.com/fj0716/p/5961022.html

标签: python

相关文章推荐

添加新评论 (无需注册,可直接评论)

已有 2 条评论

  1. 纳米热传导之小菜鸟

    实测,24行有错误
    plt.plot(x2,func(x2,fita[