Python Sympy Latex Fraction 不会在没有分解的情况下打印



我正在使用Python Sympy,求解二次曲线,并希望使用LaTex打印结果。 例如,如果结果是 x = (1 + sqrt(3((/2,我希望它通过 LaTex 打印为 \frac{1 + \sqrt{3}}{2}。 但是,Python Sympy 要么将其分成两个部分,如 \frac{1}{2} + \frac{\sqrt{3}}{2},要么将一半分解出来,如 \frac{1}{2}(1 + \sqrt{3}(。 我试图通过sympy.fraction(expr(返回分子,并查看了其他文章(Sympy - fraction操作等(,但没有一篇文章能够产生结果。

查看如何覆盖默认打印机。

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}

最新更新