9

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])
4
  • 4
    ...the complex parts are almost 0 though. convert to a float and compare. May 23, 2019 at 9:29
  • Conversely one can say that the input a should have been a complex array... May 23, 2019 at 9:35
  • fft(a) is complex May 23, 2019 at 10:22
  • So is removing imaginary part after ifft the correct implementation? Is there a reference?
    – John
    Nov 23, 2021 at 4:52

4 Answers 4

15

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

2
  • 3
    oh, that is better than my answer! May 23, 2019 at 9:40
  • 3
    I just learned about real_if_close for this answer, as I assumed numpy has to have support of it :)
    – R2RT
    May 23, 2019 at 9:43
5

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).

4

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.]
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.