# 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[0]
Q_t = time[1]

Z_fft = fft[0]
Q_fft = fft[1]
P_fft = fft[2]

#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. – Brian Borchers Sep 11 '20 at 3:16
• @MaximUmansky NumPy convolve is pretty useless. In fact , I used scipy.ndimage.convolve1d with mode=wrap and solved the problem. – Alone Programmer Sep 11 '20 at 15:10