Othmane lakhdar
Othmane lakhdar

Reputation: 1

Wrong output for FFT implementation

I'm trying to implement in Python the following Algorithm of FFT but the output is almost always wrong. I don't understand my mistakes. Can someone put some light on my mistakes ? That'll be great !

EDIT:

input [1,2] -> output [3, -1]

def FFT(A):
    n = int(len(A))
    if n == 1:
        return A
    w_n = np.exp(complex(0,2*np.pi/n))
    w = 1
    (A0,A1) = decomp(A)
    A0_star = FFT(A0)
    A1_star = FFT(A1)
    A_star0 = list()
    A_star1 = list()
    for k in range(int(n/2)):
        A_star0.append(A0_star[k] + w*A1_star[k])
        A_star1.append(A0_star[k] - w*A1_star[k])
        w = w*w_n
    A_star = A_star0 + A_star1
    return list(np.around(A_star))

def decomp(A):
   l = len(A)
   n = cpo2(l,l)
   A = fill(A,n)
   A0 = A[0::2]
   A1 = A[1::2]
   return(A0,A1)

Upvotes: 0

Views: 83

Answers (1)

Eric Backus
Eric Backus

Reputation: 1924

Two things immediately stand out to me:

  1. Your for k in range(int(n/2)): means that this only works for even values of n. And since you're calling FFT recursively, that probably means this only works when n is a power of two. Maybe that's OK, often all you care about is input lengths that are powers of two. But one of your example failures has n=3, which is not a power of two.
  2. When n=4, all your failure cases are just failures where the imaginary part of the result is the negative of what you expected. There are different definitions of FFT, which differ by the sign of the exponent in the complex exponential (the w_n in your code). It appears that you have implemented a definition which is the opposite of what np.fft.fft implements. The implementation of np.fft.fft probably follows the convention used in electrical engineering where there is a minus sign in the exponential. Your implementation seems to follow the convention used in physics where there is a plus sign in the exponential. So, try using w_n = np.exp(complex(0,-2*np.pi/n)).

There might be more issues as well, but start with those...

Upvotes: 1

Related Questions