傅立叶级数数据与NumPy:FFT与编码的拟合 [英] Fourier series data fit with numpy: fft vs coding

查看:23
本文介绍了傅立叶级数数据与NumPy:FFT与编码的拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些数据y,我想要对其进行傅立叶级数拟合。在post上,Mermoz发布了一个解决方案,使用级数的复数格式和"用黎曼和计算系数"。在另一个post上,通过FFT获得级数,并写下一个例子。

我尝试实现了这两种方法(下面的图像和代码--请注意,每次运行代码时,由于使用了numpy.随机性.Normal,将生成不同的数据),但我想知道为什么我得到了不同的结果-Riemann方法似乎"错误地转移",而FFT方法似乎"受到挤压"。我也不确定我对这一系列节目中"tau"一词的定义。感谢您的关注。

我在Windows 7上使用Spyder和Python 3.7.1

Example

import matplotlib.pyplot as plt
import numpy as np

# Assume x (independent variable) and y are the data.
# Arbitrary numerical values for question purposes:
start = 0
stop = 4
mean = 1
sigma = 2
N = 200
terms = 30 # number of terms for the Fourier series

x = np.linspace(start,stop,N,endpoint=True) 
y = np.random.normal(mean, sigma, len(x))

# Fourier series
tau = (max(x)-min(x)) # assume that signal length = 1 period (tau)

# From ref 1
def cn(n):
    c = y*np.exp(-1j*2*n*np.pi*x/tau)
    return c.sum()/c.size
def f(x, Nh):
    f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/tau) for i in range(1,Nh+1)])
    return f.sum()
y_Fourier_1 = np.array([f(t,terms).real for t in x])

# From ref 2
Y = np.fft.fft(y)
np.put(Y, range(terms+1, len(y)), 0.0) # zero-ing coefficients above "terms"
y_Fourier_2 = np.fft.ifft(Y)

# Visualization
f, ax = plt.subplots()
ax.plot(x,y, color='lightblue', label = 'artificial data')
ax.plot(x, y_Fourier_1, label = ("'Riemann' series fit (%d terms)" % terms))
ax.plot(x,y_Fourier_2, label = ("'FFT' series fit (%d terms)" % terms))
ax.grid(True, color='dimgray', linestyle='--', linewidth=0.5)
ax.set_axisbelow(True)
ax.set_ylabel('y')
ax.set_xlabel('x')
ax.legend()

推荐答案

执行两个小的修改就足以使和几乎类似于np.fft的输出。The FFTW library indeed computes these sums

1)信号的平均值c[0]要计算在内:

f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/tau) for i in range(0,Nh+1)]) # here : 0, not 1

2)输出必须按比例调整。

y_Fourier_1=y_Fourier_1*0.5

由于高频分量已被过滤,因此输出似乎受到了"挤压"。事实上,输入的高频振荡已被清除,输出看起来像移动平均线。

这里,tau实际上定义为stop-start:它对应于帧的长度。这是信号的预期周期。

如果帧与信号的周期不对应,则可以通过将信号与自身卷积并找到第一个最大值来猜测其周期。看见 Find period of a signal out of the FFT然而,它不太可能与numpy.random.normal生成的数据集一起正常工作:这是一个Additive White Gaussian Noise。由于它具有恒定的功率谱密度,它很难被描述为周期性的!

这篇关于傅立叶级数数据与NumPy:FFT与编码的拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆