user10695266
user10695266

Reputation:

Implementing DFT, inverse function not working properly

I've implemented DFT and the inverse DFT Function according to the following formulas:

The DFT function works, but when testing the inverse on the output I don't get the original series.

import numpy as np
import random

exp = np.exp
pi = np.pi

def mydft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(-2j*pi*k*i/n)
        out.append(temp)
    return np.array(out)

def myidft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(2j*pi*k*i/n)
        out.append(temp)
    return (1/n) * np.array(out)

Testing

orig = np.random.random(100)
trans = mydft(orig)

inv = myidft(trans)
print(np.allclose(inv, trans))
>>> False

print(np.allclose(trans, np.fft.fft(orig)))
>>> True

Since the original Function works and the modifications for the inverse are quite simple, I have no clue what went wrong!?

Upvotes: 1

Views: 1379

Answers (1)

yacola
yacola

Reputation: 3013

Shouldn't your test be

print(np.allclose(inv, orig))

since

orig = myidft(mydft(orig))

because when I plot your DFT

DFTandFFTcomparison

and invDFT (of DFT of original signal)

iDFTandiFFTcomparison

compared to the numpy FFT algorithm the results are exactly the same. Your implementation seems right. Your test is wrong.

Upvotes: 1

Related Questions