fmg - 5 months ago 35

LaTeX Question

I'm feeding

`sympy.latex`

`fold_short_fractions`

`True`

`>>> 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!

Answer

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)
```