Sympy: using a symbolic expression as a numerical integrand

余生长醉 提交于 2021-01-27 19:40:38

问题


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)

回答1:


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)



来源:https://stackoverflow.com/questions/40193323/sympy-using-a-symbolic-expression-as-a-numerical-integrand

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!