九州体育网 - 十年信誉网站

关于作者

Discuss / Python / 这样计算pi的速度会不会太慢了

这样计算pi的速度会不会太慢了

Topic source

Kube仔-

#1 Created at ...

def pi(N): ' 计算pi的值 '

# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
natuals = itertools.count(1, 2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
ns = itertools.takewhile(lambda x: x <= 2*N, natuals)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
ns = map(lambda n: 4/n * (1 if n % 4 == 1 else -1), ns)
# step 4: 求和:
return reduce(lambda a,b: a+b, ns)

  • 1

Reply

WARNING: You are using an old browser that does not support HTML5. Please choose a modern browser (Chrome / Microsoft Edge / Firefox / Sarafi) to get a good experience.