Search code examples
pythonnumpyfloating-pointcomplex-numbers

Why this code is getting cant convert complex to float? Or I get invalid syntax


import numpy as np
import math
freq2 = np.zeros(N)
freq2[2] = 1+(math.pi/2)j

Driving me insane... it points to the complex j operator

freq2[2] = 1+((math.pi)/2)j
SyntaxError: invalid syntax

and then this says

freq2[2] = 1+2j

Cant convert complex to float


Solution

  • There is no j operator. j is part of the syntax for an imaginary literal. Just like in MATLAB, if you want to convert a real number to imaginary, you should multiply by 1j, not just stick a j on the end of an expression:

    freq2[2] = 1+(math.pi/2)*1j
    

    instead of

    freq2[2] = 1+((math.pi)/2)j
    

    As for the TypeError, unlike in MATLAB, you can't stuff a complex number into an array of floats. You need to create the array with a complex dtype from the start:

    freq2 = np.zeros(N, dtype=complex)