python正弦函数拟合_python – 如何使用pylab和numpy将正弦曲线拟合到我的数据?

您可以在scipy中使用

least-square optimization功能将任意的功能适用于其他功能.在拟合sin函数的情况下,拟合的3个参数是偏移(‘a’),幅度(‘b’)和相位(‘c’).

只要您提供合理的第一猜测参数,优化应收敛得好.幸运的是,对于正弦函数,首先估计其中2个是容易的:可以通过以数据的平均值和振幅通过RMS(3 *标准差/ sqrt(2)).

这将导致以下代码:

import numpy as np

from scipy.optimize import leastsq

import pylab as plt

N = 1000 # number of data points

t = np.linspace(0, 4*np.pi, N)

data = 3.0*np.sin(t+0.001) + 0.5 + np.random.randn(N) # create artificial data with noise

guess_mean = np.mean(data)

guess_std = 3*np.std(data)/(2**0.5)

guess_phase = 0

# we'll use this to plot our first estimate. This might already be good enough for you

data_first_guess = guess_std*np.sin(t+guess_phase) + guess_mean

# Define the function to optimize, in this case, we want to minimize the difference

# between the actual data and our "guessed" parameters

optimize_func = lambda x: x[0]*np.sin(t+x[1]) + x[2] - data

est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]

# recreate the fitted curve using the optimized parameters

data_fit = est_std*np.sin(t+est_phase) + est_mean

plt.plot(data, '.')

plt.plot(data_fit, label='after fitting')

plt.plot(data_first_guess, label='first guess')

plt.legend()

plt.show()

编辑:我假设你知道正弦波的周期数.如果你不这样做,那就适合你了.您可以尝试通过手动绘制来猜测周期数,并尝试将其优化为第四个参数.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值