Search code examples
python-3.xsympysymbolssqrt

Is it possible to simplify expressions using the sympy library, for example sqrt (x^2) = abs (x)?


I reviewed the sympy documentation and did not find such a thing. Using the simplify method, sqrt(x**2) does not change.


Solution

  • I presume you are hoping that sqrt(x**2) will simplify to x. The problem is that this is not a valid simplification in general e.g.:

    In [23]: z = -1
    
    In [24]: z**2
    Out[24]: 1
    
    In [25]: sqrt(z**2)
    Out[25]: 1
    
    In [26]: sqrt(z**2) == z
    Out[26]: False
    

    When declaring a symbol you can set assumptions that are needed for simplification like this to be possible:

    In [27]: x = Symbol('x', real=True)
    
    In [28]: y = Symbol('y', positive=True)
    
    In [29]: sqrt(x**2)
    Out[29]: │x│
    
    In [30]: sqrt(y**2)
    Out[30]: y