Sympy 函数中没有参数

问题描述 投票:0回答:2

我有一些相当长的 sympy 表达式,我不想打印所有这些函数的参数。我正在寻找通用解决方案,因为我的方程中有三十多个函数。

示例:

a=sy.Function("a")
b=sy.Function("b")
expr=a(theta,phi)*b(zeta,theta)
sy.print_latex(expr,no_args=True)

a*b

sy.print_latex(expr)
a(theta,phi)*b(zeta,theta)

谢谢您的帮助。

sympy
2个回答
0
投票

您需要创建一个自定义乳胶打印机,并重写负责创建应用函数的乳胶代码的方法。然后,您需要通知

init_printing
您想要使用新创建的打印机。方法如下:

from sympy import *
from sympy.printing.latex import LatexPrinter
from sympy.core.function import AppliedUndef

class MyLatexPrinter(LatexPrinter):
    """ Extended Latex printer with a new option:

    applied_no_args : bool
        wheter applied undefined function should be
        rendered with their arguments. Default to False.
    """
    def __init__(self, settings=None):
        self._default_settings.update({
                "applied_no_args": False,
            }
        )
        super().__init__(settings)
        
    def _print_Function(self, expr, exp=None):
        if isinstance(expr, AppliedUndef) and self._settings["applied_no_args"]:
            if exp is None:
                return expr.func.__name__
            else:
                return r'%s^{%s}' % (expr.func.__name__, exp)
        return super()._print_Function(expr, exp)

def my_latex(expr, **settings):
    return MyLatexPrinter(settings).doprint(expr)

init_printing(latex_printer=my_latex, applied_no_args=True)
x, y, z = symbols("x:z")
f = Function("f")(x, y, z)
f

0
投票

您可以用具有相同名称的符号替换所有 AppliedUndef 对象,但您希望具有相同参数的函数表现相同吗?如果是这样,则使用编号符号来跟踪不同的参数。

from sympy import *
from sympy.core.function import AppliedUndef
from sympy.abc import x,y
reps = {}
def newfunc(name):
    i=1
    while (f:=Symbol(name + str(i))) in reps.values():
        i+=1
    return f

f,g = symbols('f g', cls=Function)
expr = f(x) + g(1, 2) + f(y)/f(x)
>>> expr.replace(
lambda x: isinstance(x, AppliedUndef), 
lambda x: reps.setdefault(x, newfunc(x.func.name)))
f1 + g1 + f2/f1
© www.soinside.com 2019 - 2024. All rights reserved.