利用互质概率有效估计Pi

2024-03-28 23:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

全部

我不是一个伟大的Python程序员,但我总是喜欢学习。所以,看完Matt Parker's latest Youtube video我就想试试。再过一会儿,我就有了一个程序:

#!/usr/bin/env python

from __future__ import division
from fractions import gcd
from random import sample
from math import sqrt

NUMSAMPLES=10000

list1 = sample(xrange(1000000),NUMSAMPLES)
list2 = sample(xrange(1000000),NUMSAMPLES)

counter = 0

for i,j in zip(list1,list2):
    if gcd(i,j) == 1:
        counter += 1

prob_coprime = counter/NUMSAMPLES
pi_estimate = sqrt(6/prob_coprime)
print "Estimate of pi: ", pi_estimate

这很管用。哈扎!但是,我想这还远远不是最有效的方法(我是一个Fortran程序员,所以我认为在循环中)。我确信有一个更好的方法来做这个计数器循环,因为我注意到随着numsample的增加,这个代码需要更长的时间。你知道吗

而且,也许,我的列表也是一个记忆猪。也许是用发电机或者其他什么东西来根据需要创建i,j?你知道吗

因此,请帮助这位老人学习:什么是更好的、高效的Python方法?你知道吗


Tags: sample方法fromimportcounterpisqrt程序员