1

I want to calculate the DFT(FFT) of a constant signal. Here is the code

import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import fft, ifft

def constant_function(x):
    return 1

t = np.arange(0.0,1,0.1)
print(type(t1))
print( np.full(t.shape, constant_function(t)))
plt.plot(t, np.full(t.shape, constant_function(t)))

freq = 1
X = fft(constant_function(t))

plt.figure(figsize = (12, 6))
plt.subplot(121)

plt.stem(freq, np.abs(X), 'b', \
         markerfmt=" ", basefmt="-b")
plt.xlabel('Freq (Hz)')
plt.ylabel('FFT Amplitude |X(freq)|')
plt.xlim(0, 1)

plt.subplot(122)
plt.plot(t, ifft(X), 'r')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()

But I get this error:

IndexError: tuple index out of range

I can't work around this error somehow! Thanks

Progman
  • 16,827
  • 6
  • 33
  • 48
Gunners
  • 55
  • 5

1 Answers1

1

The issue is not with the FFT but with your function:

def constant_function(x):
   return 1

No matter what you are putting into it (your linspace range), it's returning a constant of 1 and trying to take the FFT of a single number (1) rather than a vector of numbers. You probably want:

def constant_function(x):
    return np.ones(len(x))

Though in these cases, creating a sum of sine waves at different frequencies is usually the easiest way to test the FFT.

jonsca
  • 10,218
  • 26
  • 54
  • 62
  • Thanks! Could you please elaborate on what you mean by the last statement. Do you mean I can represent the constant function by sum of sine waves and then calculate the FFT of these sine waves. – Gunners Jun 11 '22 at 16:16
  • @Gunners Sorry, I meant more like the example here https://docs.scipy.org/doc/scipy/tutorial/fft.html#fast-fourier-transforms where they just generate a sin wave to test and make sure the algorithm is returning the proper frequency decomposition. What you are doing is fine, just not as fun as seeing the frequency components jump out when you transform – jonsca Jun 11 '22 at 20:14