如何使用蒙特卡洛方法(在python中,估计振荡曲线的整数)

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

[我正在尝试使用Monte-Carlo方法(在python中)估算以下积分:

enter image description here

我正在使用1000个随机点来估计积分。这是我的代码:

N = 1000 #total number of points to be generated

def f(x):
    return x*np.cos(x)

##Points between the x-axis and the curve will be stored in these empty lists.
red_points_x = []
red_points_y = []
blue_points_x = []
blue_points_y = []

##The loop checks if a point is between the x-axis and the curve or not.
i = 0
while i < N:
    x = random.uniform(0, 2*np.pi) 
    y = random.uniform(3.426*np.cos(3.426), 2*np.pi*np.cos(2*np.pi)) 
    if (0<= x <= np.pi and 0<= y <= f(x)) or (np.pi/2 <= x <= 3*np.pi/2 and f(x) <= y <= 0) or (3*np.pi/2 <= x <= 2*np.pi and 0 <= y <= f(x)):
        red_points_x.append(x)  
        red_points_y.append(y)   

    else:
        blue_points_x.append(x)
        blue_points_y.append(y)
    i +=1

area_of_rectangle= (2*np.pi)*(2*np.pi*np.cos(2*np.pi))

area= area_of_rectangle*(len(red_points_x))/N

print(area)

输出:

7.658813015245341

但这远非0(解析解)

这是我要绘制的区域的可视化表示:

enter image description here

我是在做错什么还是在代码中遗漏了什么?请帮助,您的帮助将不胜感激。提前非常感谢。

python python-3.x montecarlo integral
1个回答
0
投票

您在正确的轨道上!

几个提示让您上课...

  • 使您的边界框在y维度上更大,以减轻一些令人困惑的数学运算。是的,如果您“触摸”最大值和最小值,它将收敛得更快,但是暂时不要射击。哎呀,只要将其设置为-5
  • 不更改x,您设置正确0
  • 比较点以查看其是否位于“曲线下方”时,您无需检查x值...对吗?只需检查y
  • 此外,在上述点上,对于x轴以下的点,您还需要另一个类别,因为您希望将总数减少该数量。另一种“技巧”是将整个函数上移某个常数,以使整个整数为正,然后将总和减小该矩形的大小(常数*宽度)
  • 此外,在进行此操作时,请使用matplotlib绘制点,这非常简单,您可以通过收集点来将散点图与所拥有的点叠加起来,看看它看起来是否准确!

用进一步的q来评论我……您明白了!

© www.soinside.com 2019 - 2024. All rights reserved.