用任意参数替换 sympy 函数

substitute sympy function with arbitrary arguments

这应该是一项简单的任务,但我很难让它在 Sympy 中工作。 我想用特定公式替换具有任意参数的未定义函数,例如:

from sympy import *
var('a b c')
f= Function('f')
test= f(a+b)
lin= test.subs({f(c):2*(c)})
print(lin)

我要打印出来

2*(a+b)

但是,为此我必须使用

lin= test.subs({f(a+b):2*(a+b)})

我是否必须将 f 定义为 class 才能进行此替换?

当你在做的时候advanced expression manipulation like this (okay, your example is still simple), the replace method非常有用:

test.replace(f, lambda arg: 2*arg)  # returns: 2*x + 2*y

来自文档:

[replace] Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree.

文档的第二个示例显示任何函数都可以替换为另一个处理其参数的函数,如上例所示。