gpt4 book ai didi

r - 在 R 中执行时间序列的 fft

转载 作者:行者123 更新时间:2023-12-04 10:52:39 27 4
gpt4 key购买 nike

我想使用 FFT 将波浪拟合到时间序列中。
目标是绘制具有不同谐波的图,并使用它来预测 n 个数据点。

我使用的代码基于此 answer来自 @catastrophic-failure

 nff = function(y = NULL, n = NULL, up = 10L, plot = TRUE, add = FALSE, main = NULL, ...){
#The direct transformation
#The first frequency is DC, the rest are duplicated
dff = fft(y)
#The time
t = seq(from = 1, to = length(y))
#Upsampled time
nt = seq(from = 1, to = length(y)+1-1/up, by = 1/up)
#New spectrum
ndff = array(data = 0, dim = c(length(nt), 1L))
ndff[1] = dff[1] #Always, it's the DC component
if(n != 0){
ndff[2:(n+1)] = dff[2:(n+1)] #The positive frequencies always come first
#The negative ones are trickier
ndff[length(ndff):(length(ndff) - n + 1)] = dff[length(y):(length(y) - n + 1)]
}
#The inverses
indff = fft(ndff/as.integer(length(y)), inverse = TRUE)
idff = fft(dff/as.integer(length(y)), inverse = TRUE)
if(plot){
if(!add){
plot(x = t, y = y, xlab = "Time", ylab = "Data",
main = ifelse(is.null(main), paste(n, "harmonics"), main), type="l", col="green")
lines(y = Mod(idff), x = t, col = "red")
}
lines(y = Mod(indff), x = nt, ...)
}
ret = data.frame(time = nt, y = Mod(indff))
return(ret)
}

我的问题是,因为我的数据集中也有负值,所以我无法弄清楚为什么包含正值。

这是原图 data

random.x plot

与fft之后的情节相比

just the positive values

我如何调整代码,使谐波也涵盖缺失的负值,以及如何使用它来计算(预测)接下来的 n 个时间点?

最佳答案

当您尝试使用 Mod(idff) 绘制结果时出现问题。和 Mod(indff)在以下几行:

...
lines(y = Mod(idff), x = t, col = "red")
}
lines(y = Mod(indff), x = nt, ...)
Mod将始终返回与复数大小相对应的正数。

由于您正在计算具有厄米对称性(通过构造)的序列的逆 FFT,因此您应该期望得到实值结果。然而在实践中,由于舍入误差,可能存在小的虚部。通过仅使用 Re(idff) 提取实部,可以安全地忽略这些。和 Re(indff) , 如下:
...
lines(y = Re(idff), x = t, col = "red")
}
lines(y = Re(indff), x = nt, ...)

请注意,首先确认虚部与实部相比确实是非常小的数字通常是一个很好的做法,因为相反会表明频域值不具有预期的厄米对称性。

关于r - 在 R 中执行时间序列的 fft,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49501182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com