I'm trying to perform convolutions as defined mathematically $f \star g (\tau)= \int_{\mathcal{R}}f(t-\tau)g(t) dt$ in a numerical simulation. Hence, my signal is a sampling of points $f(x_i)$.
I need the computation to be precise, unbiased. Indeed, the simulation is there to show very refined effects, so I cannot discard small errors of principle. Note also that this convolution will be performed very many times over large arrays, hence it needs be efficient.
My question is if and how can I correctly compute this convolution? I have tried with the FFT algorithms already implemented in Julia (or Python, same story), but I seem to have systematic errors, as shown below. Are these the product of my lack of understanding? How else should I do?
This code is a 'test' to check that convoluting two boxes numerically gives the analytical result:
using Plots
using FFTW
using DSP
function box(x)
if abs(x) < 0.5
return 1
else
return 0
end
end
function analytical_convolved_box(x)
if x <= 0 && x > -1
return x + 1
elseif x > 0 && x < 1
return 1 - x
else
return 0
end
end
x = range(-2, stop = 2, length = 20)
dx = x[2] - x[1]
input = box.(x)
l_half = convert(Int,length(input)/2)
output = dx *conv(input, input)[l_half+1:3l_half]
plot(x, box.(x), color = :blue)
plot!(x, box.(x), seriestype = :scatter, color = :blue)
plot!(x, analytical_convolved_box.(x), color = :green)
plot!(x, analytical_convolved_box.(x), seriestype = :scatter , color = :green)
plot!(x, output, color = :black)
plot!(x, output, seriestype = :scatter, color = :black)
and for 11 points:
x = range(-2, stop = 2, length = 11)
dx = x[2] - x[1]
input = box.(x)
l_half = convert(Int,length(input)/2 - 0.5)
output = dx *conv(input, input)[l_half+1:3l_half+1]
I'd like to understand things clearly. Note that in both examples it wasn't really clear which indexes to use, so I had to essentially try and guess.