全部
我不是一个伟大的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方法?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐