9

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.

Chikorita Rai
  • 851
  • 5
  • 13
  • 17

1 Answers1

11

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
asmeurer
  • 86,894
  • 26
  • 169
  • 240