1

Is it possible to integrate custom function using sympy?

I want something like this:

def func(x, y):
    return something_with(x, y)

res = integrate(func, (y, x-2, 3), (x, 1, 2))

Is it possible?

gc5
  • 9,468
  • 24
  • 90
  • 151

1 Answers1

1

You can integrate some functions with sympy's integrate. Suppose you had the function (one variable to make it simpler)

def my_func(x):
    return x**2 + x + 1

Then you could integrate it with

x = Symbol('x')
integrate(my_func(x), (x, a, b))

Although only limited mathematical functions are likely to work.

If you only care about the numerical answer, you could try scipy's integrate.quad() (or scipy.integrate.dblquad()) which will do numerical integration, and can tackle a broader set of functions within a small error.

scipy.integrate.quad(my_func, a, b)
camz
  • 605
  • 3
  • 15
  • Hi, is there any methods to tackle variable boundaries for the integral? Something similar to this: http://stackoverflow.com/questions/30758933/double-integral-with-variable-boundaries-in-python-scipy-sympy – gc5 Jun 11 '15 at 08:13
  • I assume you mean with scipy as with sympy this is covered in the question you linked, do you need numeric integration? I haven't come across a way to do this with numeric integration, but you could try turn it into an iterated integration, and using `integrate.quad()` twice, it may be slow however. I would recommend asking another question if you need numeric and variable bounds, or maybe specify some more information about your function – camz Jun 11 '15 at 12:07
  • 1
    Oh that is your question! Didn't spot that. – camz Jun 11 '15 at 15:59