Chikorita Rai
Chikorita Rai

Reputation: 951

Separating real and imaginary parts using Sympy

I am trying to segregate real and imaginary parts of the output for the following program.

import sympy as sp
a = sp.symbols('a', imaginary=True)
b=sp.symbols('b',real=True)
V=sp.symbols('V',imaginary=True)
a=4*sp.I
b=5
V=a+b
print V

Kindly help. Thanks in advance.

Upvotes: 11

Views: 20437

Answers (1)

asmeurer
asmeurer

Reputation: 91500

The lines

b=sp.symbols('b',real=True)
V=sp.symbols('V',imaginary=True)

have no effect, because you overwrite the variables b and V in the lines

b=5
V=a+b

It's important to understand the difference between Python variables and SymPy symbols when using SymPy. Whenever you use =, you are assigning a Python variable, which is just a pointer to the number or expression you assign it to. Assigning it again changes the pointer, not the expression. See http://docs.sympy.org/latest/tutorial/intro.html and http://nedbatchelder.com/text/names.html.

To do what you want, use the as_real_imag() method, like

In [1]: expr = 4*I + 5

In [2]: expr.as_real_imag()
Out[2]: (5, 4)

You can also use the re() and im() functions:

In [3]: re(expr)
Out[3]: 5

In [4]: im(expr)
Out[4]: 4

Upvotes: 14

Related Questions