1

I have a list of strings, each of which is a complex number. The format is as below:

lr=['3.123+2.43i','0.23454-1.2134i','0.6543+0.76543i','1.12324+0.6543i']

What I want is a list of the modulus of each complex number.

2 Answers 2

6

Python natively supports complex numbers, but it uses the engineering convention of j for the imaginary unit instead of the mathematician's i.

lr = ['3+4i', '3.123+2.43i', '0.23454-1.2134i', '0.6543+0.76543i', '1.12324+0.6543i']
for s in lr:
    s = s.replace('i', 'j')
    v = complex(s)
    print(v, abs(v))

output

(3+4j) 5.0
(3.123+2.43j) 3.9570227444380457
(0.23454-1.2134j) 1.2358594465391282
(0.6543+0.76543j) 1.006971486637035
(1.12324+0.6543j) 1.2999140693138143

We can create a list of the moduli using a list comprehension:

moduli = [abs(complex(s.replace('i', 'j'))) for s in lr]
print(moduli)

output

[5.0, 3.9570227444380457, 1.2358594465391282, 1.006971486637035, 1.2999140693138143]
Sign up to request clarification or add additional context in comments.

Comments

4

Here's a variation on the 'replace i with j' solution:

In [182]: lr=['3.123+2.43i','0.23454-1.2134i','0.6543+0.76543i','1.12324+0.6543i']

Can make an array of strings:

In [183]: np.array(lr)
Out[183]: 
array(['3.123+2.43i', '0.23454-1.2134i', '0.6543+0.76543i',
       '1.12324+0.6543i'], 
      dtype='<U15')

but not complex - at least not directly

In [184]: np.array(lr,np.complex)
...
TypeError: a float is required

but there is a function that performs string replace on array elements:

In [185]: a=np.array(lr)
In [186]: np.char.replace(a,'i','j')
Out[186]: 
array(['3.123+2.43j', '0.23454-1.2134j', '0.6543+0.76543j',
       '1.12324+0.6543j'], 
      dtype='<U15')

Now that array of strings can be cast as complex

In [187]: np.char.replace(a,'i','j').astype(np.complex)
Out[187]: 
array([ 3.12300+2.43j   ,  0.23454-1.2134j ,  0.65430+0.76543j,
        1.12324+0.6543j ])

7 Comments

This method doesn't work. It will get TypeError: must be real number, not numpy.str_.
@pe-perry, what are you talking about? Ask your own question with your own data; don't tack a context-less comment onto an old answer!
sorry for not being clear. TypeError: must be real number, not numpy.str_ will be obtained when running np.char.replace(a,'i','j').astype(np.complex).
@pe-perry, I have no idea what your a looks like, so can't help.
I need to see np.char.replace(a,'i','j') before I can suggest any fixes.
|

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.