Ask Your Question

Revision history [back]

You can't really control the expression in this way because Sage does some automatic simplifications.

However, you can control how the expression is output, e.g. as $\LaTeX$:

def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')

In your example:

f, s, s_i = var("f, s, s_i")
thin_lens_formula = 1/f == 1/s + 1/s_i
sol = solve(thin_lens_formula, s)[0].rhs()
show(latex_with_few_minuses(sol))

displays

$$\frac{ f s_{i} }{ -f + s_{i} }$$