Question

Here is my complex number: I'm retrieving it out of a file.

        re, im = line[11:13]
        print( re ) # -4.04780617E-02
        print( im ) # +4.09889424E-02

At the moment it is just a pair of strings. How can I combine these into a complex number?

I've tried five times.

        z = complex( re, im )
        # ^ TypeError: complex() can't take second arg if first is a string

        z = complex( float(re), float(im) )
        # ^ ValueError: could not convert string to float: re(tot)

        z = float(re) + float(im) * 1j
        # ^ ValueError: could not convert string to float: re(tot)

        z = complex( "(" + re + im + "j)" )
        # ValueError: complex() arg is a malformed string

        z_str = "(%s%si)" % (re, im) # (-4.04780617E-02+4.09889424E-02i)
        z = complex( z_str )
        # ValueError: complex() arg is a malformed string
Was it helpful?

Solution 2

z = complex(float(re), float(im))

OTHER TIPS

Python uses 'j' as suffix for the imaginary part:

>>> complex("-4.04780617E-02+4.09889424E-02j")
(-0.0404780617+0.0409889424j)

In your case,

z_str = "(%s%sj)" % (re, im) # (-4.04780617E-02+4.09889424E-02i)
z = complex( z_str )

To convert a string into a complex number all you need to do is

c = complex(str)

Where str is a string of form "a+bj" or "a*bj" like "-5-3j"

However if you have the real and imaginary parts separately as string pairs. You can do the following

c = complex(float(re),float(im))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top