2
votes

I'm working with Python Sympy, solving a quadratic, and wanting to print the result using LaTex. For example, if the result is x = (1 + sqrt(3))/2, I would like it to print via LaTex as \frac{1 + \sqrt{3}}{2}. However, Python Sympy either splits this into two fractions, as in \frac{1}{2} + \frac{\sqrt{3}}{2}, OR factors out the half, as in \frac{1}{2}(1 + \sqrt{3}). I have tried to return the numerator via sympy.fraction(expr) and have viewed other articles (Sympy - fraction manipulation and others), but none were able to produce the result.

1

1 Answers

1
votes

Check out how to override the default printers.

import sympy
from sympy.printing.latex import LatexPrinter # necessary because latex is both a function and a module

class CustomLatexPrinter(LatexPrinter):
    def _print_Add(self, expr):
        n, d = expr.as_numer_denom()
        if d == sympy.S.One:
            # defer to the default printing mechanism
            super()._print_Add(expr)
            return
        return r'\frac{%s}{%s}' % (sympy.latex(n), sympy.latex(d)) 

# doing this should override the default latex printer globally
# adopted from "Examples of overloading StrPrinter" in the sympy documentation
sympy.printing.latex = lambda self: CustomLatexPrinter().doprint(self)

print(sympy.printing.latex((1 + sympy.sqrt(3)) / 2)) # \frac{1 + \sqrt{3}}{2}