Search code examples
pythonsympycomplex-numbers

How to convert a decimal number into symbolic representation?


With sympy, I am aware you can you do something like this:

In [37]: sqrt(8) / sqrt(27)
Out[37]: 2*sqrt(6)/9

In [38]: pprint(sqrt(8) / sqrt(27))
2⋅√6
────
 9  

There is a complex number I would like to represent in the same "symbolic" manner:

In [39]: z = complex(1,2)

The length:

In [42]: Abs(z)
Out[42]: 1.73205080756888

Now I would like to represent that number as :

In [46]: pprint(sqrt(3))
√3

Solution

  • Don't use the complex type as that can only represent complex numbers using floating point. Instead use SymPy's I:

    In [1]: from sympy import I
    
    In [2]: z = 1 + 2*I
    
    In [3]: z
    Out[3]: 1 + 2⋅ⅈ
    
    In [4]: abs(z)
    Out[4]: √5
    

    Also worth noting that sometimes SymPy can convert a float back into a guessed symbolic form:

    In [5]: e = abs(complex(1, 2))
    
    In [6]: e
    Out[6]: 2.23606797749979
    
    In [7]: from sympy import nsimplify
    
    In [8]: nsimplify(e)
    Out[8]: √5