0

There's many cases where I want symbols within the numerator and denominator of a fraction to be strictly grouped within that fraction. For instance, I might want this:

16   1
--*-----*(a + b)
37 4*a*b

instead of the more simplified

4(a + b)
--------
 37*a*b

After a lot of experiments in brute force, I would expect this:

from sympy import Mul, Rational, pretty
from sympy.abc import a, b

left = Rational(16, 37)
center = 1 / (4*a*b)
right = a + b
expr = Mul(left, center, right, evaluate=False)

print(pretty(expr))

to produce the first example I gave above.

Instead, I get this unholy abomination:

     1          
16*-----*(a + b)
   4*a*b        
----------------
       37       

This seems like it should be really easy to do, and I'm just missing something.

I did find something that works as I was writing this (given in my own answer below), but it seems like a hacky workaround, and isn't very satisfying... it makes me think this might be a bug, but I'm not sure.

drmuelr
  • 955
  • 1
  • 13
  • 30

1 Answers1

0

Thanks to this answer, I found that using UnevaluatedExpr gives me what I want. This modified snippet:

from sympy import Mul, pretty
from sympy import UnevaluatedExpr
from sympy.abc import a, b

left = UnevaluatedExpr(16) / 37
center = 1 / (4*a*b)
right = a + b
expr = Mul(left, center, right, evaluate=False)

print(pretty(expr))

gives:

16   1          
--*-----*(a + b)
37 4*a*b

However, this feels really hacky. Everything in the sympy docs seem to indicate that using Rational is the correct way to create a fraction from numeric literals.

drmuelr
  • 955
  • 1
  • 13
  • 30