ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 13 May 2019 15:17:12 -0500Rearranging expressions to minimize negative signshttp://ask.sagemath.org/question/46502/rearranging-expressions-to-minimize-negative-signs/ SageMath newbie still learning the basics here. My goal is to mostly use Sage for basic arithmetic and calculus. I'm playing with some basic equations here, but I can't seem to figure out how to rearrange the output the way I'd like.
For instance:
f, s, s_i = var("f, s, s_i")
thin_lens_formula = 1/f == 1/s + 1/s_i
solve(thin_lens_formula, s)[0]
Output:
s == -f*s_i/(f - s_i)
I'd prefer this to be expressed as `s == f*s_i / (s_i - f)`, multiplying both numerator and denominator by -1 so there is one less negative sign in total. Is there a way to do this or is Sage not really meant to be micro-managed like this?
Mon, 13 May 2019 10:14:37 -0500http://ask.sagemath.org/question/46502/rearranging-expressions-to-minimize-negative-signs/Answer by rburing for <p>SageMath newbie still learning the basics here. My goal is to mostly use Sage for basic arithmetic and calculus. I'm playing with some basic equations here, but I can't seem to figure out how to rearrange the output the way I'd like.</p>
<p>For instance:</p>
<pre><code>f, s, s_i = var("f, s, s_i")
thin_lens_formula = 1/f == 1/s + 1/s_i
solve(thin_lens_formula, s)[0]
</code></pre>
<p>Output:</p>
<pre><code>s == -f*s_i/(f - s_i)
</code></pre>
<p>I'd prefer this to be expressed as <code>s == f*s_i / (s_i - f)</code>, multiplying both numerator and denominator by -1 so there is one less negative sign in total. Is there a way to do this or is Sage not really meant to be micro-managed like this?</p>
http://ask.sagemath.org/question/46502/rearranging-expressions-to-minimize-negative-signs/?answer=46510#post-id-46510You 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} }$$Mon, 13 May 2019 15:17:12 -0500http://ask.sagemath.org/question/46502/rearranging-expressions-to-minimize-negative-signs/?answer=46510#post-id-46510