Use the Monte-Carlo method, with say 500 points, to approximate the area under the curve y = x3
for 0 ≤ x ≤ 2.
import random
def monte_carlo_approximation(num_points):
points_under_curve = 0
for i in range(num_points):
x = random.uniform(0, 2)
y = x**3
if y <= x**3:
points_under_curve += 1
area_ratio = points_under_curve / num_points
total_area = area_ratio * 2 * 2# 2 is the width of the interval [0, 2]
return total_area
what am i doing wrong
my function to appoximate the area under the curve but this is giving me the exact area instead of the approximate area
Setting
y = x**3and then immediately thereafter testing ify <= x**3is certain to always return true.That's not how the Monte Carlo method works. You're supposed to set
yto a random value, see if y <= x, and when you're done, multiply by the area of your rectangle