sympy square roots: best way to do operations on rational numbers?

418 Views Asked by At

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 -

1

There are 1 best solutions below

2
On

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