homocomputeris
homocomputeris

Reputation: 509

How to put fraction before the parenthesis in SymPy output?

I have a SymPy expression that in string format looks like

-t*(a+b+c)/2

When pretty-printed in LaTeX form (including notebook's LaTeX output), it is too tall and not very easy to read.

How can I combine the fraction and put it before the parenthesis? Like this:

(-t/2)*(a+b+c)

Code example:

from sympy import symbols, Function, Derivative, var, init_printing, pprint, latex

init_printing()
def T(y):
    var('mu')
    return -1 / (2 * mu) * Derivative(y, x, x)

def V(y):
    var('x')
    V = Function('V', commutative=True)(x)
    return V * y

def K(y):
    var('x')
    K = Function('K', commutative=True)(x)
    return K * y

def a1(y):
    var('tau', positive=True)
    return tau * (T(y) + V(y))

def c(A, B):
    def comm(y):
        return A(B(y)) - B(A(y))
    return comm

var('x')
var('t')
f = Function('psi', commutative=False)

c1k = c(a1, K)
print(latex(c1k(f(x,t)).doit().simplify()))

Prints and shows

- \frac{\tau \left(2 \frac{d}{d x} K{\left (x \right )} \frac{\partial}{\partial x} \psi{\left (x,t \right )} + \frac{d^{2}}{d x^{2}} K{\left (x \right )} \psi{\left (x,t \right )}\right)}{2 \mu}

I would like to see both in latex() and Jupyter notebook

-\frac{\tau}{2}\left(...\right)

Upvotes: 5

Views: 670

Answers (1)

user6655984
user6655984

Reputation:

SymPy 1.1.1 breaks off pieces of long fractions by default. This led to a complaint which led to a PR that disabled this behaviour in the current master branch.

To re-enable the previous default, use long_frac_ratio=2:

The allowed ratio of the width of the numerator to the width of the denominator before we start breaking off long fractions. - SymPy docs

>>> print(latex(c1k(f(x,t)).doit().simplify(), long_frac_ratio=2))
- \frac{\tau}{2 \mu} \left(2 \frac{d}{d x} K{\left (x \right )} \frac{\partial}{\partial x} \psi{\left (x,t \right )} + \frac{d^{2}}{d x^{2}} K{\left (x \right )} \psi{\left (x,t \right )}\right)

Settings can be included in init_printing:

init_printing(long_frac_ratio=2)

Upvotes: 3

Related Questions