rhomboidRhipper
rhomboidRhipper

Reputation: 119

Functions involving integration in sympy

I'd like to define a function f(x), and then define another function that it its integral.

from sympy import *
x = symbols('x')
f = lambda x: x**2

I'd like to do something like this:

g = lambda x: integrate(f(x),x)

Problem is, if I enter

g(2)

it fails. This is because it's holding the right-hand side of g(x) unevaluated until I call it. It passes the 2 into the integrate, and tries to integrate with respect to 2.

I can force the right behavior if I write:

g = lambda x: integrate(f(s),s).subs(s,x)

but that seems really clunky.

Is there a way to evaluate the integral symbolically in terms of x, and then define the function g(x) with that result?

Upvotes: 1

Views: 155

Answers (1)

smichr
smichr

Reputation: 19047

Define your g using a dummy variable foo -- x is your real variable and can't be used as the lambda's variable:

>>> g = lambda foo: integrate(f(x), (x, foo))
>>> g(2)
8/3

Upvotes: 2

Related Questions