Saten Harutyunyan
Saten Harutyunyan

Reputation: 91

What does IFFT return in Python?

I need the inverse Fourier transform of a complex array. ifft should return a real array, but it returns another complex array.

In MATLAB, a=ifft(fft(a)), but in Python it does not work like that.

a = np.arange(6)
m = ifft(fft(a))
m # Google says m should = a, but m is complex

Output :

array([0.+0.00000000e+00j, 1.+3.70074342e-16j, 2.+0.00000000e+00j,
       3.-5.68396583e-17j, 4.+0.00000000e+00j, 5.-3.13234683e-16j])

Upvotes: 9

Views: 8073

Answers (4)

FlyingTeller
FlyingTeller

Reputation: 20609

You are mistaken in "Ifft should return a real array". If you want a real valued output (i.e. you have the fft of real data and now want to perform the ifft) you should use irfft.

See this example from the docs:

>>> np.fft.ifft([1, -1j, -1, 1j])
array([ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j])   #Output is complex which is correct
>>> np.fft.irfft([1, -1j, -1])
array([ 0.,  1.,  0.,  0.])   #Output is real valued

Upvotes: 3

prosti
prosti

Reputation: 46469

You can test like this:

import numpy as np
from numpy import fft
a = np.arange(6)
print(a)
f = np.fft.fft(a)
print(f)
m = np.fft.ifft(f)
print(m)

[0 1 2 3 4 5]
[15.+0.j         -3.+5.19615242j -3.+1.73205081j -3.+0.j
 -3.-1.73205081j -3.-5.19615242j]
[0.+0.j 1.+0.j 2.+0.j 3.+0.j 4.+0.j 5.+0.j]

To get the real part only you can use:

print(m.real) # [0. 1. 2. 3. 4. 5.]

Upvotes: 4

hiro protagonist
hiro protagonist

Reputation: 46921

if the imaginary part is close to zero you could discard it:

import numpy as np

arr = np.array(
    [
        0.0 + 0.00000000e00j,
        1.0 + 3.70074342e-16j,
        2.0 + 0.00000000e00j,
        3.0 - 5.68396583e-17j,
        4.0 + 0.00000000e00j,
        5.0 - 3.13234683e-16j,
    ]
)

if all(np.isclose(arr.imag, 0)):
    arr = arr.real
# [ 0.  1.  2.  3.  4.  5.]

(that's what real_if_close does in one line as in R2RT's answer).

Upvotes: 5

R2RT
R2RT

Reputation: 2146

The imaginary part is result floating precision number calculation error. If it is very small, it rather can be dropped.

Numpy has built-in function real_if_close, to do so:

>>> np.real_if_close(np.fft.ifft(np.fft.fft(a)))
array([0., 1., 2., 3., 4., 5.])

You can read about floating system limitations here: https://docs.python.org/3.8/tutorial/floatingpoint.html

Upvotes: 15

Related Questions