2
$\begingroup$

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.

$\endgroup$

1 Answer 1

4
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ 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! $\endgroup$
    – Sha
    Commented Jan 20, 2021 at 20:42
  • $\begingroup$ @Sha Ok, added another script for the case $z \in [0,1-x]$. $\endgroup$ Commented Jan 20, 2021 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.