Tom
Tom

Reputation: 233

Sympy: using a symbolic expression as a numerical integrand

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)

Upvotes: 3

Views: 324

Answers (1)

Stelios
Stelios

Reputation: 5531

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)

Upvotes: 4

Related Questions