Yes, you can assume that an expression under a square root is positive using assumptions and simplify(). However, sympy does not automatically assume non-negative values for symbolic expressions unless explicitly specified.
Example 1: Handling sqrt(x^2) = x
You can assume x is positive using the symbols function:
from sympy import symbols, sqrt, simplifyIf x is not explicitly assumed to be positive, sympy will return sqrt(x^2) = |x| instead.
Example 2: Handling sqrt((x - 2)^3) = (x - 2)*sqrt(x - 2)
You need to ensure that x - 2 is positive:
y = symbols('y', positive=True) # Let y = x - 2 be positiveFor an arbitrary expression, you can try using simplify() along with assumptions, but sympy may not always simplify it in the way you expect.
Regards,
Pratyksh
It seems not :
>>> from sympy import * >>> x=symbols("x") >>> with assuming(Q.positive(x)): sqrt(x**2).simplify() ... sqrt(x**2) >>> with assuming(Q.positive(x)): sqrt(x**2).factor() ... sqrt(x**2) >>> with assuming(Q.positive(x)): sqrt(x**2).expand() ... sqrt(x**2)But :
>>> y=symbols("y", positive=True) >>> sqrt(y**2) yThis is a bit inconsistent…
Hello Paul,
Expanding on the above answer ,there are a few more different ways to assume the positiveness of expressions under the square root in SymPy (using the new assumptions) . However, it seems that we still cannot directly simplify terms of the form x**(3/2) to x * sqrt(x), if that is the intended goal. That said, expressions where the exponent in the numerator is even can indeed be reduced, as demonstrated in the following examples:
from sympy import * x = symbols('x') with assuming(Q.positive(x)): # all assumptions can be put within assuming () print(refine(sqrt(x**2))) # Output: x# Using refine syntax of type refine(expr, assumptions) print(refine(sqrt(x**2), Q.positive(x))) # Output: x # A few more examples: print(refine(sqrt(x**3), Q.positive(x))) # Output: x**(3/2) print(refine(sqrt(x**4), Q.positive(x))) # Output: x**2 print(refine(sqrt(x**5), Q.positive(x))) # Output: x**(5/2)
This approach effectively simplifies square roots for even exponents, while odd exponents retain their fractional form.
That said, if anyone in the community knows a way to express odd exponents (e.g., y**(3/2)) in the form of y * sqrt(y), it would be nice to know that!
Best regards,
Krishnav Bajoria.
--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/sympy/b75269b4-7d2b-423b-939f-7d7d4322e670n%40googlegroups.com.