0

Since i want square roots to be simplified, I've come across this workaround:

from sympy import sqrt, factor, simplify

_sqrt = sqrt
sqrt = lambda x: factor(simplify(_sqrt(x)))

# do maths operations with sqrt...

But it's too slow and I don't think it's the most suitable method one can use So is there any other way to work with square roots and simplify them - automatically -

Amin Guermazi
  • 1,632
  • 9
  • 19

1 Answers1

0

SymPy automatically simplifies rational arguments to sqrt, but it is possible to write rationals in a manner such that they are not explicitly rational (as in your previous post):

>>> eq
sqrt((-9/10 + 6*sqrt(3)/5)**2 + (6/5 + 9*sqrt(3)/10)**2)

sqrt will only simplify an explicit Rational argument. Expansion of the base of the argument reveals that it is a Rational and the sqrt will simplify it:

>>> eq.base.expand()
9
>>> sqrt(9) == 3
True

Better than expand in such cases where you need to flatten an expression involving powers is the _mexpand function:

>>> from sympy.core.function import _mexpand as flat
>>> flat(eq)
3
smichr
  • 16,948
  • 2
  • 27
  • 34
  • So should I replace the `factor(symplify(sqrt(x)))` with `_mexpand(sqrt(x))` ? – Amin Guermazi Apr 19 '21 at 21:48
  • In your lambda expression, yes. But if your `x` might have ratios of expressions then `sqrt = lambda x: _sqrt(cancel(x))` would be better. By doing this you are basically saying, "Whenever I use sqrt I want to make sure there are no factors un-cancelled in the expression." – smichr Apr 19 '21 at 22:39