Stef1611
Stef1611

Reputation: 2399

SYMPY: How to simplify sqrt ratio?

I would like to simplify sqrt ratios. For example :

import sympy as sp
a,b=sp.symbols("a b", real=True)
myExpr=sp.sqrt(b/a)*sp.sqrt(a/b)

Why does not myExpr simplify to 1 ?

I tried many things that does not work :

myExpr.simplify()
...
myExpr.refine(sp.Q.positive(a)&sp.Q.positive(b)&sp.Q.real(a)&sp.Q.real(b))

How can I simplify such expressions ?

My expressions are much more complex than this simple case. It is a sum of product of terms. For example, one term of the sum is :

myExpr=sp.sqrt((2*a**2+1-2*a*sp.sqrt(a**2+1))/(a**2+1-a*sp.sqrt(a**2+1)))/sp.sqrt(a**2+1-a*sp.sqrt(a**2+1))*sp.sqrt((2*b**2+1-2*b*sp.sqrt(b**2+1))/(b**2+1-b*sp.sqrt(b**2+1)))/sp.sqrt(b**2+1-b*sp.sqrt(b**2+1))

And its simplification (done by hand) is

mySimplif=sp.sqrt((2*a**2+1-2*a*sp.sqrt(a**2+1)))/(a**2-a*sp.sqrt(a**2+1)+1)+sp.sqrt((2*b**2+1-2*b*sp.sqrt(b**2+1)))/(b**2-b*sp.sqrt(b**2+1)+1)

To be complete, I use this workaround (not very convenient):

c=sp.symbols("c",positive=True)
myExpr.subs(sp.sqrt(a**2+1-a*sp.sqrt(a**2+1)),c).subs(c,sp.sqrt(a**2+1-a*sp.sqrt(a**2+1))).subs(sp.sqrt(b**2+1-b*sp.sqrt(b**2+1)),c).subs(c,sp.sqrt(b**2+1-b*sp.sqrt(b**2+1)))

Thanks for answer.

Upvotes: 0

Views: 132

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14530

You need a and b to be positive rather than just real:

In [15]: a, b = symbols('a, b', positive=True)

In [16]: sqrt(b/a)*sqrt(a/b)
Out[16]: 1

Otherwise if they can be negative then you could have e.g. a = -1 and b = 1 in which case the simplification would not be valid:

In [21]: a = sympify(-1)

In [22]: b = sympify(1)

In [23]: sqrt(a/b)*sqrt(b/a)
Out[23]: -1

Upvotes: 2

Related Questions