用任意参数替换 sympy 函数 [英] substitute sympy function with arbitrary arguments

查看:34
本文介绍了用任意参数替换 sympy 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This should be an easy task, but I'm having a hard time getting it to work in Sympy. I want to substitute an undefined function with arbitrary arguments with a specific formula for example:

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 定义为一个类才能执行此替换?

Do I have to define f as a class in order to do this substitution?

推荐答案

当你在做 高级表达式操作像这样(好吧,你的例子仍然很简单),replace 方法 非常有用:

When you're doing advanced expression manipulation like this (okay, your example is still simple), the replace method is very useful:

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

来自文档:

[replace] 遍历表达式树并从树的底部到顶部执行匹配子表达式的替换.

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

文档的第二个示例表明,任何函数都可以被另一个对其参数起作用的函数替换,如上例所示.

The 2nd example of the docs show that any function can be replaced by another that works on its arguments, as shown above for your example as well.

这篇关于用任意参数替换 sympy 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆