Skip to main content
 首页 » 编程设计

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

2025年01月19日8myhome

我正在使用 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 manipulation 等),但没有一个能够产生结果。

请您参考如下方法:

查看 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}