蒙特卡洛和区域计算

时间:2011-10-29 18:11:02

标签: python matlab

应该接近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 个答案:

答案 0 :(得分: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