英文:
Is it possible to substitute a function definition into a sympy expression?
问题
假设我定义了一个sympy函数f
,并且有表达式f(5) * f(2)
。是否可以替换我选择的函数为f并计算上述表达式?例如,假设我选择f(x)为x**2。那么,上述表达式将返回100。
我知道的唯一方法是以下代码:
x = sp.symbols('x')
F = sp.Function('F')
expr = F(2)*F(5)
expr = expr.subs({F(2):4,F(5):25}) #我的不好的解决方案
expr #打印出100
但当函数必须在许多点上进行评估时,或者如果您事先不知道值时,这变得非常困难。有什么更好的方法可以进行上述替换吗?
英文:
Suppose I define a sympy function f
and I have the expression f(5) * f(2)
. Is it possible to substitute a function of my choice for f and evaluate the above expression? For example, lets say I choose f(x) to be x**2. Then, the above expression would return 100.
The only way I know how to do this is the following code:
x = sp.symbols('x')
F = sp.Function('F')
expr = F(2)*F(5)
expr = expr.subs({F(2):4,F(5):25}) #my bad solution
expr #prints out 100
But this becomes very difficult to do when the function has to be evaluated at many points, or if you do not know the values beforehand. What is the better way to do the above substitutions?
答案1
得分: 1
你可以根据提供的函数类型使用subs
或replace
来完成这个操作:
from sympy import *
f = Function('f')
eq = f(2)*f(5)
eq.subs(f, cos)
# cos(2)*cos(5)
g = lambda x: 1/(x + 1)
eq.replace(lambda x: x.func == f, lambda x: g(x.args[0]))
# 1/18
英文:
You can do this with subs or replace depending on what type of function your are providing:
from sympy import *
f = Function('f')
eq = f(2)*f(5)
eq.subs(f, cos)
# cos(2)*cos(5)
g = lambda x: 1/(x + 1)
eq.replace(lambda x: x.func == f, lambda x: g(x.args[0]))
# 1/18
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论