Search code examples
pythonsympycomplex-numbers

Parameterized complex numbers in SymPy


Consider the following Python code:

import sympy as sp

t = sp.symbols('t', real=True)

y = sp.parse_expr(input("y = "))
real_imag = y.as_real_imag()
print("Real:", real_imag[0])
print("Imaginary:", real_imag[1])

When the input to y variable is "t**2 + t*I", the output is:

Real: re(t)**2 - im(t)**2 - im(t)
Imaginary: 2*re(t)*im(t) + re(t)

Why the output is not like this?

Real: t**2
Imaginary: t

The input must be taken from the user, it is essential. And the output must be without re() and im() functions. Is there a way to do so?

Tried:

  • re() and im() functions instead of as_real_imag(),
  • sympify() instead of parse_expr(),
  • simplify() and expand(). But nothing changed.

Solution

  • The symbol that you create with real=True will not be used by parse_expr unless you pass it in:

    In [11]: t = symbols('t', real=True)
    
    In [12]: y = parse_expr('t**2 + I*t', local_dict={'t':t})
    
    In [13]: y
    Out[13]: 
     2      
    t  + ⅈ⋅t
    
    In [14]: y.as_real_imag()
    Out[14]: 
    ⎛ 2   ⎞
    ⎝t , t⎠