蒙特卡罗方法。,

问题描述 投票:0回答:1

使用蒙特卡罗方法,例如 500 个点,来近似面积 在曲线 y = x3

对于 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 

我做错了什么

我的函数近似曲线下的面积,但这给了我精确的面积而不是近似的面积

javascript python jupyter-notebook area pyspider
1个回答
0
投票

设置

y = x**3
,然后立即测试
y <= x**3
是否一定总是返回 true。

蒙特卡罗方法不是这样工作的。你应该将

y
设置为随机值,看看 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
© www.soinside.com 2019 - 2024. All rights reserved.