2021年2月7日星期日

Python: Integration over Multiple Dimensions of function taking an array input

I am having difficulty computing multiple integrals of functions with taking array inputs. I would like to use scipy.integrate's nquad function because I need to be able to integrate from -np.inf to np.inf (I'm working with probability density functions). The issue is nquad expects a function to be formulated like this:

function(x_1, x_2, ..., x_n)

The functions I need to integrate over take this form:

function(np.array([x_1, x_2, ..., x_n]))

Is there a way to change a function that takes an array to accept multiple arguments? If not, is there an alternative to nquad? I tried using quadpy, but it said my integral was over 31, when the actual value was 1.

Thanks for the help.

Edit: I have found the solution. I fixed the issue by creating a wrapper function taking in *args, converting args to a numpy array, and integrating the wrapper function.

Here's an example:

from scipy.integrate import nquad  from scipy.stats import multivariate_normal    mean = [0., 0.]  cov = np.array([[1., 0.],                  [0., 1.]])    bivariate_normal = multivariate_normal(mean=mean, cov=cov)    def pdf(*args):      x = np.array(args)      return bivariate_normal.pdf(x)    integration_range = [[-18, 18], [-18, 18]]    nquad(pdf, integration_range)    Output: (1.000000000000001, 1.3429066352690133e-08)  
https://stackoverflow.com/questions/66095037/python-integration-over-multiple-dimensions-of-function-taking-an-array-input February 08, 2021 at 10:01AM

没有评论:

发表评论