Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating real and imaginary parts using Sympy

Tags:

python

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.

like image 462
Chikorita Rai Avatar asked Sep 19 '14 06:09

Chikorita Rai


1 Answers

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
like image 57
asmeurer Avatar answered Oct 01 '22 00:10

asmeurer