Ask Your Question

Revision history [back]

Here is something that works on your second example:

def evaluate_with_units(expr):
    expr_canonical = expr.canonicalize_radical()
    num = expr_canonical.numerator().polynomial(ring=RR['meter,second'])
    denom = expr_canonical.denominator().polynomial(ring=RR['meter,second'])
    return SR((num.lc() / denom.lc()) * (num/num.lc()) / (denom / denom.lc()))

Example:

sage: stuck=123.0*sqrt(units.length.meter*(units.length.meter/units.time.second^2)/(17.0*tan(0.1*pi) + 1))/cos(0.2*pi)
sage: evaluate_with_units(stuck)
59.5254442433757*meter/second

Here is something that works on your second example:

def evaluate_with_units(expr):
    expr_canonical = expr.canonicalize_radical()
    var_names = [str(v) for v in expr_canonical.variables()]
    poly_ring = PolynomialRing(RR, names=var_names)
    num = expr_canonical.numerator().polynomial(ring=RR['meter,second'])
expr_canonical.numerator().polynomial(ring=poly_ring)
    denom = expr_canonical.denominator().polynomial(ring=RR['meter,second'])
expr_canonical.denominator().polynomial(ring=poly_ring)
    return SR((num.lc() / denom.lc()) * (num/num.lc()) / (denom / denom.lc()))

Example:

sage: stuck=123.0*sqrt(units.length.meter*(units.length.meter/units.time.second^2)/(17.0*tan(0.1*pi) + 1))/cos(0.2*pi)
sage: evaluate_with_units(stuck)
59.5254442433757*meter/second