sympylcapy

Complex numbers in sympy


I am using lcapy together with sympy and trying to process complex numbers from a circuit.

I have the following sympy expression:

import sympy
from lcapy import j

expr = sympy.parse_expr('L*w_0*(C*R*w_0 - I)')
expr

Output:

L⋅w₀⋅(C⋅R⋅w₀ - ⅉ)

expr above is an complex expression with being the imaginary number. Can I use sympy and remove the brackets from expr in order to view it in the more canonical form for complex numbers as

w₀^2⋅R⋅L⋅C - ⅉ⋅w₀⋅L

And does sympy have support for handling complex numbers? I want to get the argument of expr which should be:

arctan(L⋅w₀ / w₀^2⋅R⋅L⋅C)

Solution

  • I can do (in an isympy session):

    In [13]: expr
    Out[13]: L⋅w₀⋅(C⋅R⋅w₀ - ⅈ)
    
    In [14]: expr.expand()
    Out[14]: 
            2         
    C⋅L⋅R⋅w₀  - ⅈ⋅L⋅w₀
    

    edit

    try

    atan2(im(expr), re(expr))
    

    https://docs.sympy.org/latest/modules/functions/elementary.html

    Refining the variables:

    In [53]: C,L,R,w_0=symbols('C L R w_0',real=True, positive=True)    
    In [54]: expr=L*w_0*(C*R*w_0-I)
    
    In [55]: expr
    Out[55]: L⋅w₀⋅(C⋅R⋅w₀ - ⅈ)
    
    In [56]: expr.expand()
    Out[56]: 
            2         
    C⋅L⋅R⋅w₀  - ⅈ⋅L⋅w₀
    
    In [57]: im(_),re(_)
    Out[57]: 
    ⎛               2⎞
    ⎝-L⋅w₀, C⋅L⋅R⋅w₀ ⎠
    

    Now the atan2 is simplified:

    In [59]: atan2(*_)
    Out[59]: 
         ⎛  1   ⎞
    -atan⎜──────⎟
         ⎝C⋅R⋅w₀⎠
    

    And arg does the same:

    In [60]: arg(_56)
    Out[60]: arg(C⋅R⋅w₀ - ⅈ)
    
    In [62]: arg(expr)
    Out[62]: arg(C⋅R⋅w₀ - ⅈ)
    
    In [77]: arg(expr)._eval_rewrite_as_atan2(expr)
    Out[77]: 
         ⎛  1   ⎞
    -atan⎜──────⎟
         ⎝C⋅R⋅w₀⎠