Ask Your Question

Revision history [back]

One possible trick is to replace sqrt(2) by a variable t and sqrt(3) by a variable d, so you get a polynomial in t and d, and introduce a variable z for sqrt(6), and then reduce the polynomial in t and d by t*d - z using some monomial ordering where t*d > z, e.g. the lexicographic ordering with t > d > z, so that all instances of t*d are replaced by z, and then you can substitute z by sqrt(6):

def collect_sqrt2sqrt3_to_sqrt6(expr):
    expr_poly = expr.subs({sqrt(2) : var('t'), sqrt(3) : var('d')})
    R = PolynomialRing(SR, names=['t', 'd', 'z'], order='lex')
    t, d, z = R.gens()
    poly = expr_poly.polynomial(ring=R)
    poly_collected = poly.reduce([t*d - z])
    return SR(poly_collected.subs({z : sqrt(6), t : sqrt(2), d : sqrt(3)}))

Example:

sage: a = sqrt(2)*sqrt(3)+6
sage: collect_sqrt2sqrt3_to_sqrt6(a)
sqrt(6) + 6

With some more effort this could be generalized to detect which square roots appear in the expression, etc.