Reputation: 16518
I am using scipy.integrate.quad(f, a, b, args=(c,))
to integrate function f
between a
and b
, adding another parameter c
. You can think about f
as
f = lambda x, y: x*y
As I understand it, the function requires a
, b
, c
to be float values. However, I have many integrals to solve, all with the same function, just over vectors of a
, b
, and c
. Iterating through all the vectors is quite inefficient. Is there any way to speed up / vectorize this operation?
Upvotes: 4
Views: 3858
Reputation: 323
It looks that meanwhile numpy has responded to this by implementing numpy.vectorize with an example covered in integrate. Here is modified example with two variables:
fun2int = lambda x, a: np.sqrt(x+a)
intfun = lambda a: integrate.quad(fun2int, 0, 4, args=(a))[0]
vec_int = np.vectorize(intfun)
vec_int(np.linspace(0,2,5))
Out[1]: array([5.33333333, 6.12825877, 6.78689326, 7.37435069, 7.91234089])
There is also integrate.quad_vec (scipy.version of 1.4.1), but I did not test that.
Upvotes: 3
Reputation: 26090
Alas, this is not supported by integrate.quad
.
You might find better luck with using gaussian quadratures yourself: scipy.integra.fixed_quad
chokes on array_like input, but the lower-level routines which compute roots and weights should work. See "Roots and weights for orthogonal polynomials" section here.
YMMV though.
Upvotes: 3
Reputation: 21574
If I understood well the problem, I would just run the function over an array of a,b,c
parameters. For instance, set an array of two sets of a,b,c
as:
a = np.array([[0.1,0.2,0.3], [0.9,0.8,0.3]])
then set an empty list to store results:
L = []
and loop through the array:
for a,b,c in a:
b = integrate.quad(f, a, b, args=(c,))
L.append(b)
The result is a list of tuples:
[(0.004500000000000001, 4.996003610813206e-17), (-0.025499999999999995, 2.8310687127941485e-16)]
Maybe there is a more elegant way, but hope that helps.
Upvotes: 0