# How to take convolution of two arrays in Python by using NumPy?

Generally, we know that if we have this relation between Fourier transforms of three functions in frequency domain as:

$$\mathfrak{F}\{\mathsf{P}(t)\} = \mathfrak{F}\{\mathsf{Z}(t)\}\mathfrak{F}\{\mathsf{Q}(t)\}$$

We should have this relationship in the time domain as:

$$\mathsf{P}(t) = \int \mathsf{Z}(\tau) \mathsf{Q}(t-\tau) d\tau$$

Now I have this in Python:

import numpy as np

time = np.genfromtxt('time-data.txt',delimiter=',').T

fft = np.genfromtxt('fft-data.txt',delimiter=',',dtype=np.complex_).T

Z_t = time
Q_t = time

Z_fft = fft
Q_fft = fft
P_fft = fft

#Shows that indeed Z_fft is the Fourier transform of Z_t
assert (np.fft.irfft(Z_fft,n=len(Q_t)) == Z_t).all()

#Shows that indeed Q_fft is the Fourier transform of Q_t
assert (np.fft.irfft(Q_fft,n=len(Q_t)) == Q_t).all()

#Shows that indeed Z_fft = P_fft / Q_fft
assert (np.divide(P_fft,Q_fft) == Z_fft).all()

P_t = np.fft.irfft(P_fft,n=len(Q_t))

P_t_from_convolve = np.convolve(Z_t,Q_t,mode='same')

#Expect to see that P_t = P_t_convolve but it's not the case!
assert (P_t == P_t_from_convolve).all()


Is there any reason that $$\int \mathsf{Z}(\tau) \mathsf{Q}(t-\tau) d\tau \neq \mathfrak{F^{-1}}\{\mathfrak{F} \{ \mathsf{P}(t) \} \}$$?

These are the data files here:

• Generally it's necessary to 0-pad a discrete time series in order for periodic FFT based convolution to work in the same way as conventional convolution. It's also extremely numerically unstable to deconvolve by spectral division. Sep 11, 2020 at 3:16
• @MaximUmansky NumPy convolve is pretty useless. In fact , I used scipy.ndimage.convolve1d with mode=wrap and solved the problem. Sep 11, 2020 at 15:10