Skip to content

Instantly share code, notes, and snippets.

@binary10
Last active November 5, 2022 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binary10/941db9d7bae3ecf1ae40c5104babf8b8 to your computer and use it in GitHub Desktop.
Save binary10/941db9d7bae3ecf1ae40c5104babf8b8 to your computer and use it in GitHub Desktop.
# Initialize two signals with arbitrary length
n, m = 5, 7
convolution_length = n+m-1
u = np.random.randint(0, 255, n)
v = np.random.randint(0, 255, m)
# Convolve the two signals
cv = sp.signal.convolve(u, v)
assert cv.shape[0] == convolution_length
# Now, apply the Convolution Theorem.
## Copy and pad signal. Padding is necessary to match the convolution length.
vv = v.copy()
vv.resize(n+m-1, refcheck=False)
uu = u.copy()
uu.resize(n+m-1, refcheck=False)
# Compute FFT
fu = fft(uu)
fv = fft(vv)
# Inverse FFT of frequency signal
fcv = ifft(fu * fv)
# Does the inverse transform of the product of the Fourier transforms of the signals equal the convolution of the two signals?
assert np.allclose(fcv, cv)
@timvieira
Copy link

this was helpful - thanks!

I tweaked it to support the convolution of any two vectors (of possibly different lengths).

# Initialize a signal
n, m = 5, 7
u = np.random.randint(0, 255, n)
v = np.random.randint(0, 255, m)

# Convolve u and v
cv = sp.signal.convolve(u, v)

assert cv.shape[0] == n+m-1

# Copy and pad signal
vv = v.copy()
vv.resize(n+m-1, refcheck=False)

uu = u.copy()
uu.resize(n+m-1, refcheck=False)

# Compute FFT
fu = fft(uu)
fv = fft(vv)

# Inverse FFT of frequency signal
fcv = ifft(fu * fv)

assert np.allclose(fcv, cv)

@binary10
Copy link
Author

binary10 commented Apr 27, 2022

@timviera I'm glad it helped you -- thanks for sharing back. I especially enjoyed learning about np.allclose()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment