fft of a constant function in python

Viewed 48

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

1 Answers

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.

Related