import re from sage.all import * def discrim(p,x): """ Takes a polynomial in arbitrary variables as the first argument. All variables except the one specified by the second argument are treated as constants. Returns the discriminant of the polynomial. """ vars = var_weights(p,x) R = singular.ring(0, '('+ ",".join(vars.keys()) +')', 'Wp(' + ",".join(vars.values()) + ')') singular.set_ring(R) d=singular.deg(p) l=singular.lead(p)/(singular(x)**d) return singular.eval('(' + repr((-1)**(d*(d-1)/2)*singular.resultant(p,singular.diff(p,x),x)) + ')/' + repr(l)) def var_weights(p,x): Rvar_rex = re.compile('([a-zA-Z_]+\w*)($|\+|\-|\s|\*|\/|\^|(|))') p_parse = Rvar_rex.findall(repr(p)) Rvars = dict([(var,'0') for (var,d1,d2) in p_parse]) Rvars[x]='1' return Rvars