python 傅里叶_Python中的Fourier级数

如果您愿意,可以使用我为此目的编写的名为symfit的包,非常接近sympy代码进行数据拟合。它基本上使用sympy接口包装scipy。使用symfit,可以执行以下操作:from symfit import parameters, variables, sin, cos, Fit

import numpy as np

import matplotlib.pyplot as plt

def fourier_series(x, f, n=0):

"""

Returns a symbolic fourier series of order `n`.

:param n: Order of the fourier series.

:param x: Independent variable

:param f: Frequency of the fourier series

"""

# Make the parameter objects for all the terms

a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))

sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))

# Construct the series

series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)

for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))

return series

x, y = variables('x, y')

w, = parameters('w')

model_dict = {y: fourier_series(x, f=w, n=3)}

print(model_dict)

这将打印出我们想要的符号模型:

^{pr2}$

接下来,我将把它与一个简单的step函数结合起来,向您展示它是如何工作的:# Make step function data

xdata = np.linspace(-np.pi, np.pi)

ydata = np.zeros_like(xdata)

ydata[xdata > 0] = 1

# Define a Fit object for this model and data

fit = Fit(model_dict, x=xdata, y=ydata)

fit_result = fit.execute()

print(fit_result)

# Plot the result

plt.plot(xdata, ydata)

plt.plot(xdata, fit.model(x=xdata, **fit_result.params).y, color='green', ls=':')

这将打印:Parameter Value Standard Deviation

a0 5.000000e-01 2.075395e-02

a1 -4.903805e-12 3.277426e-02

a2 5.325068e-12 3.197889e-02

a3 -4.857033e-12 3.080979e-02

b1 6.267589e-01 2.546980e-02

b2 1.986491e-02 2.637273e-02

b3 1.846406e-01 2.725019e-02

w 8.671471e-01 3.132108e-02

Fitting status message: Optimization terminated successfully.

Number of iterations: 44

Regression Coefficient: 0.9401712713086535

并得出以下曲线图:

就这么简单!我把剩下的留给你想象。有关详细信息,请参阅documentation here。在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值