Karl Yngve Lervåg
Karl Yngve Lervåg

Reputation: 1715

Sympy: Simplifying square roots of squares

Sympy does not seem to be able to simplify an expression where the square root of a square of a variable is involved:

In [28]: a = x**2
In [29]: b = a**(1/2)
In [30]: b
Out[30]: 
    0.5
⎛ 2⎞   
⎝x ⎠   
In [31]: b.simplify()
Out[31]: 
    0.5
⎛ 2⎞   
⎝x ⎠   

I do not get this to work with other variants of simplify, in particular I would have thought that b.powsimp() should work.

In [32]: b.powsimp()
Out[32]: 
    0.5
⎛ 2⎞   
⎝x ⎠   

Does anyone know why this does not work, or what I am doing wrong?

Upvotes: 3

Views: 3337

Answers (3)

asmeurer
asmeurer

Reputation: 91490

The function you want is powdenest. If passed the force=True parameter, it will ignore assumptions

>>> powdenest(sqrt(x**2), force=True)
x

Upvotes: 3

Krastanov
Krastanov

Reputation: 6549

There are two problems with your example.

First sqrt(x**2)==x only for positive real numbers.

Second, for SymPy 1/2 and 0.5 are not the same things. The first is a Rational instance, the second is a float instance.

Finally, an example:

>>> x = Symbol('x', real=True)
>>> (x**2)**(1./2)
∣x∣**1.0
>>> (x**2)**(S(1)/2) # S() is short for sympify()
∣x∣

sympify transforms python objects to more adequate SymPy objects.

Upvotes: 6

halex
halex

Reputation: 16403

I assume you declare x as x = Symbol('x'). If you change it to x = Symbol('x', real=True) the expression should be simplified. You can find the reason why you have to explicitly state that your variable is real in the sympy bugtracker.

Upvotes: 3

Related Questions