# nquad Integration in SciPy

I am trying to self-learn SciPy and evaluate the following quadruple integral using scipy.integrate.nquad:

$$\int_{0}^{1} \int_{0}^{1} \int_{0}^{1} \int_{0}^{1-x} (w+y) \:dz \:dy \:dx \:dw$$

I wrote the following code:

from scipy import integrate

def f(z, y, x, w):
return w + y

def bounds(z):
return [0, 1-z]

I = integrate.nquad(f, [bounds, [0,1], [0,1], [0,1]])

print(I)


However, it gives the following error:

bounds() takes 1 positional argument but 3 were given


Any help to solve this quadruple integral is much appreciated.

## 1 Answer

Assuming it is the $$w$$ variable that has the range $$[0,1-x]$$

from  scipy.integrate import nquad

def func(w,x,y,z):
return w+y

def range_z():
return [0,1]

def range_y(z):
return [0,1]

def range_x(y, z):
return [0,1]

def range_w(x, y, z):
return (0,1-x)

res=nquad(func, [range_w, range_x, range_y, range_z])
print(res)


Running it produces 0.41666666666666674 which matches the analytic answer 5/12.

Assuming it is the $$z$$ variable that has the range $$[0,1-x]$$,

from  scipy.integrate import nquad

def func(z,y,x,w):
return w+y

def range_w():
return [0,1]

def range_x(w):
return [0,1]

def range_y(x,w):
return [0,1]

def range_z(y,x,w):
return (0,1-x)

res=nquad(func, [range_z, range_y, range_x, range_w])
print(res)


In this case the answer from the code is 0.5 which matches the analytic answer 1/2.

• Actually it is the z variable that has the range [0,1−x], and the analytic solution is 0.5. Based on your answer I figured out how to get this correct value, please consider editing your answer in order to accept it as a correct one. Thank you! – Sha Jan 20 at 20:42
• @Sha Ok, added another script for the case $z \in [0,1-x]$. – Maxim Umansky Jan 20 at 20:57