0

Here is my complex number. *I retrieved 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
1
  • what do you mean by combine? what are you trying to achieve? I see two real numbers. One positive and another negative. How do you want them to combine to a complex number? Commented Jan 21, 2014 at 14:02

3 Answers 3

5

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

Note to self: Mathematicians say i, engineers say j. Computer code is engineering :)
2
z = complex(float(re), float(im))

1 Comment

Thanks -- this is the simplest way! Due to an error elsewhere in my code, I was getting garbage values for re, im.
0

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

Comments

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.