【发布时间】:2015-08-31 10:35:34
【问题描述】:
我写了这个方法:
def approx_pi(n, p):
"""
Approximates Pi by putting dots in a square and counting
the dots in the max possible circle in that square.
:param n: Number of dots
:param p: Precision used for urandom
:return: Approximation of Pi
"""
in_circle = 0
k = 100
max_int = (2**(8*p)-1)
for i in range(n):
# get two random Numbers between 0 and 1
x = int.from_bytes(os.urandom(p), byteorder='big')/max_int
y = int.from_bytes(os.urandom(p), byteorder='big')/max_int
if x ** 2 + y ** 2 <= 1:
in_circle += 1
# Just for debugging
if (i+1) % k == 0:
k = int(k*1.01)
print(i, '\t',4*in_circle/i)
sys.stdout.flush()
return 4*in_circle/n
在我的大多数测试运行中,它在 3.141 处稳定下来,然后在该值附近发散。 这是urandom的弱点吗?但如果是这样,为什么 pi 不朝一个方向移动?还是我的代码有问题。
【问题讨论】:
-
如果您使用
x = int.from_bytes(os.urandom(p), byteorder='big')(y模拟)和if x ** 2 + y ** 2 <= max_int**2,它是否有效?只是为了消除不精确的浮点运算。 -
n和p的价值观是什么? -
@Stefan,我选择 n := 1.000.000.000 和 p \in {1, 2, 3, 4}。
-
@koffein 这真的是一个好点!不幸的是,到目前为止它似乎没有任何效果,但我正在增加数字并进行更多测试。
-
@Finn 还有一件事:选择
n>max_int**2没有任何好处,因为在这种情况下,您还可以采用所有可能的(x,y)-组合,您会得到更好的结果。
标签: python random statistics pi