Ejemplo n.º 1
0
def symbolic_to_polynomial(f, vars):
    # Rewrite a symbolic expression as a polynomial over SR in a given
    # list of variables.

    poly = f.polynomial(QQ)
    allvars = poly.variables()

    indices = []
    for x in allvars:
        try:
            indices.append(vars.index(x))
        except ValueError:
            indices.append(None)

    R = PolynomialRing(SR, len(vars), vars)
    res = R.zero()
    for coeff, alpha in zip(poly.coefficients(), poly.exponents()):
        if type(alpha) == int:
            # Once again, univariate polynomials receive special treatment
            # in Sage.
            alpha = [alpha]

        term = R(coeff)
        for i, e in enumerate(alpha):
            if not e:
                continue
            if indices[i] is None:
                term *= SR(allvars[i]**e)
            else:
                term *= R.gen(indices[i])**e
        res += term
    return res