H.W.10

# integral f(x)=x+y+z HW10
# with interval x=[0, 1], y=[0, 1], z=[0, 1]
import random as rd
import numpy as np
def f(x, y, z):
return x+y+z
if __name__=="__main__":
N=100000
rd.seed()
xlim=[0, 1]
ylim=[0, 1]
zlim=[0, 1]
sum=0.
for i in range(N): # sum_{i=0}{N} f(x_i, y_i, z_i)
x=xlim[0]+(xlim[1]-xlim[0])*rd.random() # x_i
y=ylim[0]+(ylim[1]-ylim[0])*rd.random() # y_i
z=zlim[0]+(zlim[1]-zlim[0])*rd.random() # z_i
sum+=f(x, y, z) # f(x_i, y_i, z_i)
# sum_{i=0}{N} f(x_i, y_i, z_i)*(x_2-x_1)*(y_2-y_1)*(z_2-z_1)/N
sum=sum*(xlim[1]-xlim[0])*(ylim[1]-ylim[0])*(zlim[1]-zlim[0])/N
print("integral f(x, y, z)=x+y+z")
print("from x=0 to 1, from y=0 to 1, from z=0 to 1:")
print(sum)
from wolframalpha
integral_0^1 integral_0^1 integral_0^1 (x + y + z) dz dy dx = 3/2 = 1.5