Search code examples
pythonpython-3.xnumpyscipynumerical-integration

ValueError when performing integration in Numpy


I am receiving a ValueError which I cannot decifer. I am tryig to perform a simple integration task, using the integrate.quad on a lambda function. Here is the code:

import numpy as np
p = np.arange(0,1,1/1000)
x = 0
y = 1
z = 0.9
pdfl = lambda p: 2*(p-x)/((y-x)*(z-x)) if p<z else 2*(y-p)/((y-x)*(y-z))
h = lambda pp: integrate.quad(lambda p: p*pdfl(p), 0, pp)

In this code, pdfl is the probability density function of a (skewed) triangular distribution. Now, this function works for particular numbers, that is, h(0.5) gives us an answer as desired. However, I would like to have h evaluated at each of the elements in p. But when I do h(p), I get the exception:

  File "d:\Anaconda3\lib\site-packages\scipy\integrate\quadpack.py", line 315, in quad
    points)

  File "d:\Anaconda3\lib\site-packages\scipy\integrate\quadpack.py", line 364, in _quad
    if (b != Inf and a != -Inf):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Any advice on how to overcome this error? Thank you.


Solution

  • This error, as you can see from the side bar questions, is the result of using an array in a context that expects a scalar True/False.

    My guess is the quad is testing the bounds, pp against inf. It works fine when you give it one bounds, e.g. 0.5, but produces this error when you give it an array of bounds, p. quad is designed to work with one set of bounds at a time, not an array.

    I think you need to do something like

    res = [h(pp) for pp in p]
    

    that is, iterate, performing the integration for one bound value at a time.