在sympy中,有没有办法抑制函数参数的写法,比如写f而不是f(x)?

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

我正在 Jupyter Notebook 中使用一个变量的许多函数进行微积分。

我使用乳胶显示结果

from sympy import *
from IPython.display import display, Math, Latex 
init_printing()

当我打印类似

Function('f')('x')
的内容时,它会显示为
f(x)
。我希望它的结果是
f
。这可能吗?

python jupyter-notebook sympy
2个回答
0
投票

对于那些仍在寻找解决方案的人,您可以将以下函数用于任意数量的函数输入:

def display_no_args(expr):
    functions = expr.atoms(Function)
    reps = {}

    for fun in functions:
        reps[fun] = Symbol(fun.name)

    display(expr.subs(reps))

0
投票

我的建议是制作一个类生成函数。

import sympy as sp

def my_Function(name):
    def __new__(cls, *args, **options):
        cls.short_latex = True
        function = sp.Function.__new__(cls, *args, **options)
        return function

    def _latex(cls, printer):
        _func = printer._print(cls.func)
        _args = printer._print(cls.args)
        if cls.short_latex:
            return r'%s' % (_func)
        else:
            return r'%s%s' % (_func, _args)

    return type(name, (sp.Function,),{'__new__':__new__,'_latex': _latex})

x = sp.symarray('x',3)
f = sp.Matrix([ my_Function(f'f_{i}')(*x) for i in range(3)])
f
© www.soinside.com 2019 - 2024. All rights reserved.