Use Monte Carlo integration to estimate the integral of a function. Also calculate the error-> limit(1,0) ∫ 𝑥 ^2 (3𝑥 + 1)𝑑x
from scipy import random
import numpy as np
a = 0
b = 1
N = 1000
ar = np.zeros(N)
for i in range(len(ar)):
ar[i] = random.uniform(a, b)
integral = 0.0
def f(x):
return x**2*(3*x+1)
for i in ar:
integral += f(i)
ans = (b-a)/float(N)*integral
print(f"The answer {ans}.")
Comments
Leave a comment