Skip to content Skip to sidebar Skip to footer

Creating Custom Printing For Sympy.derivative

Say I have a function f(x,y), I want partial derivative of f w.r.t to x appear as \partial_{x}^{n} f(x,y) so I created the following class class D(sp.Derivative): def _latex(se

Solution 1:

The problem is that you haven't overridden doit from the parent class and it returns plain Derivative objects rather than your subclass. Rather than creating a new Derivative class I suggest to create a new printer class:

from sympy import *

from sympy.printing.latex import LatexPrinter

classMyLatexPrinter(LatexPrinter):
    def_print_Derivative(self, expr):
        differand, *(wrt_counts) = expr.args
        iflen(wrt_counts) > 1or wrt_counts[0][1] != 1:
            raise NotImplementedError('More code needed...')
        ((wrt, count),) = wrt_counts
        return'\partial_{%s} %s)' % (self._print(wrt), self._print(differand))

x, y = symbols('x, y')
f = Function('f')
expr = (x*f(x, y)).diff(x)

printer = MyLatexPrinter()

print(printer.doprint(expr))

That gives x \partial_{x} f{\left(x,y \right)}) + f{\left(x,y \right)}

You can use init_printing(latex_printer=printer.doprint) to make this the default output.

Post a Comment for "Creating Custom Printing For Sympy.derivative"