Skip to content

Instantly share code, notes, and snippets.

@sradc
Last active June 1, 2021 19:38
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 sradc/4bad981fac00dd77bba6bb9c421dfb31 to your computer and use it in GitHub Desktop.
Save sradc/4bad981fac00dd77bba6bb9c421dfb31 to your computer and use it in GitHub Desktop.
import math
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
N = 13
# Taking only the real part of the Fourier transform, then applying the inverse Fourier transform:
reconstructed = np.fft.ifft(np.fft.fft(signal).real).real
# Getting the exact same result, by flipping and averaging the signal:
signal = 2 * (np.random.random(N) - .5)
flipped = signal.copy()
flipped[1:] = np.flip(signal[1:])
s1 = (signal + flipped) / 2
# Plots:
plt.figure(figsize=(5, 5), dpi=100, facecolor='w')
plt.subplot(3, 1, 1)
plt.ylim([-1, 1])
plt.plot(s1)
plt.title('(x[n]+x[-n])/2')
plt.subplot(3, 1, 2)
plt.ylim([-1, 1])
plt.plot(reconstructed)
plt.title('ifft(fft(x).real).real')
plt.subplot(3, 1, 3)
plt.ylim([-1, 1])
plt.plot(s1 - reconstructed)
plt.title('Error')
plt.tight_layout()
plt.show()
@sradc
Copy link
Author

sradc commented Jun 1, 2021

Output:

dft-real-only_vs_symmetric

@sradc
Copy link
Author

sradc commented Jun 1, 2021

The mathematics of above was explained to me in this reddit thread. Thanks to /u/dijisza and /u/binaryblade.

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