May I profits from this question to get better understanding of the fft
. Following the wikipedia formula for fourier series (Fourier series - Wikipedia) I though that this simple code will reconstruct a real signal from its harmonics:
using FFTW, Plots
fs = 256
Δt = 1 / fs
P = 1.0
x = 0.0:Δt:P
y = [sin(2 * pi * 7 * t) + sin(2 * pi * 15 * t) + sin(2 * pi * 30 * t) for t in x] # mixture of simple wave signal
plot(x, y, legend = false)
Fy = rfft(y)
freq = 0.0:(fs / length(y)):(fs / 2)
N = length(Fy)
ak = real.(Fy ./ N)
bk = imag.(Fy ./ N)
yr = [ak[1] / 2 for _ in x]
for i in 2:N
yr .+= ak[i] .* cos.(2 * pi * freq[i] .* x) .+ bk[i] .* sin.(2 * pi *freq[i] .* x)
end
plot!(x, yr)
But actually this give me a signal that is flip from the x axis and shift in time by Δt
, to get the correct reconstruction I found that I have to do:
yr = [ak[1] / 2 for _ in x]
for i in 2:N
yr .+= ak[i] .* cos.(2 * pi * freq[i] .* (x .+ Δt)) .+ bk[i] .* sin.(2 * pi *freq[i] .* (x .+ Δt))
end
yr .= -yr
May I ask why ?