[我正在尝试使用Monte-Carlo方法(在python中)估算以下积分:
我正在使用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(解析解)
这是我要绘制的区域的可视化表示:
我是在做错什么还是在代码中遗漏了什么?请帮助,您的帮助将不胜感激。提前非常感谢。
您在正确的轨道上!
几个提示让您上课...
用进一步的q来评论我……您明白了!