Search code examples
pythonmathscipyintegral

Why does scipy's quadrature function throw an error when using arrays?


I have two versions of a snippet; one works and one doesn't.

This works:

f = lambda x : x * 2.0 * pi
print(scipy.integrate.quadrature(f, 0.0, 1.0))

This fails:

f = lambda x : math.exp(x * 2.0 * pi)`
print(scipy.integrate.quadrature(f, 0.0, 1.0))

With the error:

TypeError: only size-1 arrays can be converted to Python scalars

I don;t understand both are scalar functions, why is one accepted but the other is not?


Solution

  • You may have intended your functions to operate on scalars, but unless you pass vec_func=False, scipy.integrate.quadrature will assume your functions can safely take and operate elementwise over arrays.

    As it happens, your first f can indeed handle arrays, even though you didn't intend it to. Your second f uses math.exp, which only handles scalars.