Search code examples
python-3.xsympysymbolssqrt

I can't get abs(a) if I use sqrt(parse_expr('a**2')).simplify(). Python outputs sqrt(a**2). The sympy library


This code gives sqrt(a^2), I need it to give abs(a).

from sympy import sqrt, simplify, symbols
from sympy.parsing.sympy_parser import parse_expr
a = symbols('a', real=True)
expr = parse_expr('a**2')
sqrt(simplify(expr)).simplify()

Solution

  • from sympy import sqrt, simplify, symbols
    a = symbols('a', real=True)
    expr = eval('a**2')
    sqrt(simplify(expr)).simplify()