Monte-Carlo method.,

52 Views Asked by At

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

1

There are 1 best solutions below

0
Frank Yellin On

Setting y = x**3 and then immediately thereafter testing if y <= x**3 is certain to always return true.

That's not how the Monte Carlo method works. You're supposed to set y to a random value, see if y <= x, and when you're done, multiply by the area of your rectangle

def monte_carlo_approximation(num_points):
    points_under_curve = 0

    for i in range(num_points):
        x = random.uniform(0, 2)
        y = random.uniform(0, 8)
        if y <= x**3:
            points_under_curve += 1

    area_ratio = points_under_curve / num_points
    total_area = 2 * 8 * area_ratio
    return total_area