问题
I have this 2-dimensional integral with dependent limits. The function can be defined in Python as
def func(gamma, u2, u3):
return (1-1/(1+gamma-u3-u2))*(1/(1+u2)**2)*(1/(1+u3)**2)
where the limits of u3
is from 0 to gamma
(a positive real number), and the limits of u2
is from 0 to gamma-u3
.
How can I implement this using scipy.integrate.nquad? I tried to read the documentation, but it was not easy to follow, especially I am relatively new to Python.
Extension: I would like to implement a numerical integration for an arbiraty K
, where the integrand in this case is given by (1-1/(1+gamma-uk-....-u2))*(1/(1+uK)**2)*...*(1/(1+u2)**2)
. I wrote the function that takes a dynamic number of arguments as follows:
def integrand(gamma, *args):
'''
inputs:
- gamma
- *args = (uK, ..., u2)
Output:
- (1-1/(1+gamma-uk-....-u2))*(1/(1+uK)**2)*...*(1/(1+u2)**2)
'''
L = len(args)
for ll in range(0, L):
gamma -= args[ll]
func = 1-1/(1+gamma)
for ll in range(0, L):
func *= 1/((1+args[ll])**2)
return func
However, I am not sure how to do the same for the ranges, where I will have one function for the ranges, where uK
ranges from 0 to gamma
, u_{K-1}
ranges from 0 to gamma-uK
, ...., u2
ranges from 0 to gamma-uK-...-u2
.
回答1:
Here is a simpler method using scipy.integrate.dblquad instead of nquad
:
Return the double (definite) integral of func(y, x) from x = a..b and y = gfun(x)..hfun(x).
from scipy.integrate import dblquad
def func(u2, u3, gamma):
return (1-1/(1+gamma-u3-u2))*(1/(1+u2)**2)*(1/(1+u3)**2)
gamma = 10
def gfun(u3):
return 0
def hfun(u3):
return gamma-u3
dblquad(func, 0, gamma, gfun, hfun, args=(gamma,))
It seems that gfun
and hfun
do not accept the extra arguments, so gamma
has to be a global variable.
Using nquad
, after many trial and error:
from scipy.integrate import nquad
def func(u2, u3, gamma):
return (1-1/(1+gamma-u3-u2))*(1/(1+u2)**2)*(1/(1+u3)**2)
def range_u3(gamma):
return (0, gamma)
def range_u2(u3, gamma):
return (0, gamma-u3)
gamma = 10
nquad(func, [range_u2, range_u3], args=(gamma,) )
Useful quote from the source code of tplquad
:
# nquad will hand (y, x, t0, ...) to ranges0
# nquad will hand (x, t0, ...) to ranges1
And from the nquad
documentation, the order of the variables is reversed (same for dblquad
):
Integration is carried out in order. That is, integration over x0 is the innermost integral, and xn is the outermost
Generic case with k
nested integrations:
from scipy.integrate import nquad
import numpy as np
def func(*args):
gamma = args[-1]
var = np.array(args[:-1])
return (1-1/(1+gamma-np.sum(var)))*np.prod(((1+var)**-2))
def range_func(*args):
gamma = args[-1]
return (0, gamma-sum(args[:-1]))
gamma, k = 10, 2
nquad(func, [range_func]*k, args=(gamma,) )
来源:https://stackoverflow.com/questions/51602089/implementing-numerical-integration-using-scipy-integrate-nquad