mpourreza
mpourreza

Reputation: 177

Recursive FFT discards the imaginary part

I am trying to implement recursive FFT.

import numpy as np
from math import e, pi

def rdft(a):
    n = a.size
    if n == 1:
        return a
    i = complex(0, 1)
    w_n = e ** (2 * i * pi / float(n))
    w = 1
    a_0 = np.zeros(int(math.ceil(n / 2.0)))
    a_1 = np.zeros(n / 2)
    for index in range(0, n):
        if index % 2 == 0:
            a_0[index / 2] = a[index]
        else:
            a_1[index / 2] = a[index]
    y_0 = rdft(a_0)
    y_1 = rdft(a_1)
    y = np.zeros(n)
    for k in range(0, n / 2):
        y[k] = y_0[k] + w * y_1[k]
        y[k + n / 2] = y_0[k] - w * y_1[k]
        w = w * w_n
return y



if __name__ == "__main__":
    a = np.array([1, 0,0, -2])
    print rdft(a)

It gives me the following error:

[-1.  1.  3.  1.]
/path/file.py:22: ComplexWarning: Casting complex values to real discards the imaginary part y[k] = complex(y_0[k] + w * y_1[k])
/path/file.py:23: ComplexWarning: Casting complex values to real discards the imaginary part y[k + n / 2] = y_0[k] - w * y_1[k]

I'm not familiar with complex calculations in Python. The real values are correct but as it says it discards the imaginary part.

Upvotes: 2

Views: 1944

Answers (1)

Mr. T
Mr. T

Reputation: 12410

You try to cast complex numbers to a numpy array that has been defined as float. To overcome this problem, define y as a numpy array with complex values:

y = np.zeros(n, dtype = complex)

Output after this change:

[-1.+0.j  1.+2.j  3.+0.j  1.-2.j]

If you want to know more about numpy data types, read the numpy user guide.

Upvotes: 2

Related Questions