fmg - 1 year ago 176
LaTeX Question

# Sympy's latex printer, folding short fractions

I'm feeding

sympy.latex
a string involving fractions and I'd like to get its latex representation with fractions "folded", i.e., typeset as 3/2 rather than as \frac{3}{2}. I'm setting the
fold_short_fractions
keyword argument to
True
, but the results I'm getting are inconsistent:

>>> from sympy.parsing.sympy_parser import parse_exp
>>> from sympy import latex
>>>
>>> print(latex(parse_expr("3*x**2/y"))) # OK
\frac{3 x^{2}}{y}
>>> print(latex(parse_expr("3*x**2/y"), fold_short_frac=True)) # OK
3 x^{2} / y
>>>
>>> print(latex(parse_expr("3/2"))) # OK
\frac{3}{2}
>>> print(latex(parse_expr("3/2"), fold_short_frac=True)) # No!!
\frac{3}{2}


As you can see, it refuses to fold the numerical fraction 3/2, although it seems to be okay with symbolic expressions. Does anyone have an explanation/fix/workaround for this? Thanks!

This is a bug in the SymPy latex printer. It isn't looking at the fold_short_frac option for rational numbers. I've got a fix here.

In the meantime, you can use this is as workaround:

from sympy.printing.latex import LatexPrinter

class MyLatexPrinter(LatexPrinter):
def _print_Rational(self, expr):
if expr.q != 1:
sign = ""
p = expr.p
if expr.p < 0:
sign = "- "
p = -p
if self._settings['fold_short_frac']:
return r"%s%d / %d" % (sign, p, expr.q)
return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
else:
return self._print(expr.p)

def latex(expr, **settings):
return MyLatexPrinter(settings).doprint(expr)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download