Search code examples
sympypretty-print

Customizing SymPy's LaTeX Representation of Positive Infinity to Display +\infty


I've noticed that in SymPy, the default LaTeX representation for positive infinity is \infty. I'm seeking a method to customize this representation to show +\infty instead.

I've explored here https://docs.sympy.org/latest/modules/printing.html sympy.printing.pretty.pretty_symbology, which maps SymPy objects to their respective LaTeX representations. However, I couldn't find a way to modify the representation for the infinity symbol.

Is there a specific configuration or setting within SymPy that permits users to customize the LaTeX representation of positive infinity?


Solution

  • Your question mention Latex and pretty print: those are two separate features of SymPy. This answer is about Latex: if you need to modify pretty printing it should be similar.

    The official way to customize printing is to create a new printer by sub-classing the one you intend to modify.

    from sympy import *
    from sympy.printing.latex import LatexPrinter
    
    class MyPrinter(LatexPrinter):
        def _print_Infinity(self, v):
            print("It never gets here!")
            return r"+\infty"
    
    def myprinter(expr, **settings):
        return MyPrinter(settings).doprint(expr)
    
    init_printing(latex_printer=myprinter, use_latex=True)
    
    S.Infinity
    

    enter image description here

    However, this is a case where it doesn't work, because sympy.core.numbers.Infinity (the class representing +infinity), defines the method _latex.

    When LatexPrinter (or a sub-class of it) parses an object which defines this method, it executes it, no matter if you defined a custom method on the printer for that specific object. This, I believe, should not be the case. Please, consider opening an issue on Sympy.

    So, we are forced to override a private method on the specific class. Here's how:

    from sympy import *
    # you only need to do this once, after sympy is loaded
    def my_infinity_latex(self, printer):
        return r"+\infty"
    S.Infinity.func._latex = my_infinity_latex
    
    S.Infinity
    

    enter image description here