是否可以通过Symphy中的symbols()指定偏导数符号?

2024-05-29 06:54:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将其中一个变量象征性地表示为偏导数,如:

dF_dx=符号('dF/dx')

这样显示器(dF_dx)将显示为:

enter image description here

有办法吗?对于新手来说,官方的参考资料不是很清楚。多谢各位


Tags: df官方符号显示器导数参考资料新手办法
1条回答
网友
1楼 · 发布于 2024-05-29 06:54:02

^{}当前根据^{}决定是否使用rounded d符号。requires_partial函数检查表达式使用了多少个自由符号,如果它使用了多个符号,那么它将使用四舍五入的d符号,否则它将只使用d

要覆盖此行为,我们只需将一个自定义LatexPrinter类传递给init_printing

from sympy import *
from sympy.printing.latex import LatexPrinter
from sympy.core.function import _coeff_isneg, AppliedUndef, Derivative
from sympy.printing.precedence import precedence, PRECEDENCE

class CustomPrint(LatexPrinter):
    def _print_Derivative(self, expr):
        diff_symbol = r'\partial'

        
        tex = "" 
        dim = 0
        for x, num in reversed(expr.variable_count):
            dim += num
            if num == 1:
                tex += r"%s %s" % (diff_symbol, self._print(x))
            else:
                tex += r"%s %s^{%s}" % (diff_symbol,
                                        self.parenthesize_super(self._print(x)),
                                        self._print(num))

        if dim == 1:
            tex = r"\frac{%s}{%s}" % (diff_symbol, tex) 
        else:
            tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex) 

        if any(_coeff_isneg(i) for i in expr.args):
            return r"%s %s" % (tex, self.parenthesize(expr.expr,
                                                  PRECEDENCE["Mul"],
                                                  is_neg=True,
                                                  strict=True))

        return r"%s %s" % (tex, self.parenthesize(expr.expr,
                                                  PRECEDENCE["Mul"],
                                                  is_neg=False,
                                                  strict=True))
        
def custom_print_func(expr, **settings):
    return CustomPrint().doprint(expr)
    
    
x = symbols('x')
F = Function('F')(x)
init_printing(use_latex=True,latex_mode="plain",latex_printer=custom_print_func)

dF_dx = F.diff(x)

display(dF_dx)

输出:

enter image description here


有关如何使用自定义latex打印机,请参见this post as well

这篇文章中的所有代码都是可用的

相关问题 更多 >

    热门问题