Sympy:使用符号表达式作为数值被积函数 [英] Sympy: using a symbolic expression as a numerical integrand
问题描述
我需要以符号方式操作一个函数,然后对该函数进行数值积分.如何在被积函数中正确使用我的表达式 f.如果这甚至是明智的做法,我该如何正确使用lambdify?非常感谢.
from sympy import *导入 scipy.integrate 作为集成r = symbols('r') #定义符号f = diff(r*r) #进行符号操作def integrand(x): #定义要积分的函数return lamdify(x, f) #将变量x交换为fresult =integrate.quad(integrand, 0, 5) #数值积分打印(结果)
lambdify
返回一个函数对象,不需要使用包装函数.另请注意,lambdify
的第一个参数应该是表示包含在sympy 表达式(在本例中为 f_sym
)作为其第二个参数提供.
import sympy as sp从 scipy.integrate 导入四边形r = sp.symbols('r')f_sym = sp.diff(r*r, r)f_lam = sp.lambdify(r, f_sym)结果 = 四边形(f_lam, 0, 5)打印(结果)
<块引用>
(25.0, 2.7755575615628914e-13)
I need to manipulate a function symbolically, and then numerically integrate the function. How do I correctly use my expression f in the integrand function. How do I use lambdify correctly if that is even the sensible way to do it? Many thanks.
from sympy import *
import scipy.integrate as integrate
r = symbols('r') #define symbol
f = diff(r*r) #carry out symbolic manipulation
def integrand(x): #define function to integrate
return lambdify(x, f) #swap variable x into f
result = integrate.quad(integrand, 0, 5) #integrate numerically
print(result)
lambdify
returns a function object, there is no need to use a wrapper function. Also note that the first argument of lambdify
should be a tuple of variables representing sympy
symbols (in this case, r
) that are included in the sympy expression (in this case, f_sym
) provided as its second argument.
import sympy as sp
from scipy.integrate import quad
r = sp.symbols('r')
f_sym = sp.diff(r*r, r)
f_lam = sp.lambdify(r, f_sym)
result = quad(f_lam, 0, 5)
print(result)
(25.0, 2.7755575615628914e-13)
这篇关于Sympy:使用符号表达式作为数值被积函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!