0

I wrote a short Python code to compute the Discrete Fourier Transform of a signal. Here is the code.

#import packages
from numpy import *
import math
import cmath

def computedft(x):
#function to calculate the dft of a signal
#Inputs : x(t) time domain signal
#output : K Fourier coff magnitudes

        N=len(x)
        #Caluclate omeag for DFT
        omega=2* math.pi /N
        for k in range(N):
        #outer loop is for each Fourier Coff
                sum=0
                for i in range(N):
                        sum=sum+x[i]*exp(- math.sqrt(-1)*k*omega*i)
                X[k]=sum
        return X

Then I went to ipython and gave these commands

In [1]: x=[9,6,7,8,9,-4,-8,-1]

In [2]: import computedft

In [3]: computedft.computedft(x)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

~/Documents/<ipython console> in <module>()

~/Documents/computedft.py in computedft(x)
     16                 sum=0
     17                 for i in range(N):
---> 18                         sum=sum+x[i]*exp(- math.sqrt(-1)*k*omega*i)
     19                 X[k]=sum
     20         return X

ValueError: math domain error

I dont understand why I am getting this error. I have included the cmath package, so thus it should be able to multiply complex numbers. But why doesnt it work?

1
  • You could replace "math.sqrt(-1)" with "1j" Commented Aug 22, 2023 at 9:37

1 Answer 1

2

use cmath instead of math:

In [123]: math.sqrt(-1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-123-5234f21f3b4d> in <module>()
----> 1 math.sqrt(-1)

ValueError: math domain error

In [124]: import cmath

In [125]: cmath.sqrt(-1)
Out[125]: 1j
Sign up to request clarification or add additional context in comments.

3 Comments

ok, I got it, so if we import cmath package then we dont need to import math package separately, I have another doubt: when I make changes to the code I m using vim editor then I run in ipython import computedft and then run the python file, it doesnt get updated and still shows the error before I made the change. If I quit ipython and restart it, then it compiles the new code. Why does this happen?
once you've imported a package (e.g. computedft), it's cached in dictionary sys.modules, next time you import it, it's omitted. So you need to restart ipython kernel, or reload(computedft) ;)
You could just use "1j" as it is an (imaginary) literal [imaginary meaning imaginary number]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.