是不是可以将一个函数定义替换到 sympy 表达式中?

huangapple go评论61阅读模式
英文:

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

你可以根据提供的函数类型使用subsreplace来完成这个操作:

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

huangapple
  • 本文由 发表于 2023年6月15日 04:28:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定