I have a lot of data to integrate over and would like to find a way of doing it all with just matrices, and would be willing to compromise on accuracy for a performance boost. What I have in mind is something like this:
import numpy
import scipy
a = np.array([1,2,3])
def func(x):
return x**2 + x
def func2(x):
global a
return a*x
def integrand(x):
return func(x)*func2(x)
integrated = quad(integrand, 0, 1)
So I am trying to integrate each element in the array that comes out of integrand
.
I'm aware that there is a possibility of using numpy.vectorize()
like this:
integrated = numpy.vectorize(scipy.integrate.quad)(integrand, 0, 1)
but I can't get that working. Is there a way to do this in python?
Solution
Well now that I learnt a bit more python I can answer this question if anyone happens to stable upon it and has the same question. The way to do it is to write the functions as though they are going to take scalar values, and not vectors as inputs. So follow from my code above, what we would have is something like
import numpy as np
import scipy.integrate.quad
a = np.array([1, 2, 3]) # arbitrary array, can be any size
def func(x):
return x**2 + x
def func2(x, a):
return a*x
def integrand(x, a):
return func(x)*func2(x, a)
def integrated(a):
integrated, tmp = scipy.integrate.quad(integrand, 0, 1, args = (a))
return integrated
def vectorizeInt():
global a
integrateArray = []
for i in range(len(a)):
integrate = integrated(a[i])
integrateArray.append(integrate)
return integrateArray
Not that the variable which you are integrating over must be the first input to the function. This is required for scipy.integrate.quad. If you are integrating over a method, it is the second argument after the typical self
(i.e. x
is integrated in def integrand(self, x, a):
). Also the args = (a)
is necessary to tell quad
the value of a
in the function integrand
. If integrand
has many arguments, say def integrand(x, a, b, c, d):
you simply put the arguments in order in args
. So that would be args = (a, b, c, d)
.