蒙特卡洛与面积计算

1 投票
1 回答
1621 浏览
提问于 2025-04-17 05:15

这个值应该接近0.3

$ cat monte.py 
import random,math
density=int(1e6)
x = [random.uniform(0,1)*7*math.pi for _ in range(density)]
y = [random.uniform(0,1) for _ in range(density)]
i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)]

print sum(i)/(float(density)*10.0)*7*math.pi

$ python monte.py 
0.350184850795

我正在尝试重写下面的代码,但不知道为什么这段Python代码的结果根本不接近。

x = rand(1, 1000000)*7pi;
y = rand(1, 1000000);
i = sin(x).* cos(x) >y;
Area3 = (sum(i) / 10000000)*7pi;

1 个回答

2

我发现你给的MATLAB和Python版本的结果是一样的……你确定MATLAB的结果是~2,而不是~0.35吗?

比如说:

MATLAB:

x = rand(1, 1000000)*7*pi;
y = rand(1, 1000000);
i = sin(x).* cos(x) >y;
Area3 = (sum(i) / 10000000)*7*pi

这个结果是:0.3511

你的纯Python版本:

import random,math
density=int(1e6)
x = [random.uniform(0,1)*7*math.pi for _ in range(density)]
y = [random.uniform(0,1) for _ in range(density)]
i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)]

print sum(i)/(float(density)*10.0)*7*math.pi

这个结果是:0.347935156296

基于Numpy的版本:

import numpy as np
x = np.random.random(1e6) * 7 * np.pi
y = np.random.random(x.size)
i = np.sin(x) * np.cos(x) > y
print 7 * np.pi * i.sum() / (10 * x.size)

这个结果是:0.350475133957

撰写回答