Separating real and imaginary parts with Sympy

I am trying to extract the 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.

+3


source to share


1 answer


Lines

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

      

have no effect as you are overwriting variables b

and V

in strings

b=5
V=a+b

      

It is 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 assigned. 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 a method as_real_imag()

like

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

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

      

You can also use functions re()

and im()

:

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

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

      

+3


source







All Articles