Discuss / Python / 按步骤来

按步骤来

Topic source

苏生不语_

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce
# 计算pi的值
def pi(N):
    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
    odd = itertools.count(1, 2)
    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
    ns = itertools.takewhile(lambda x: x <= 2*N-1, odd)
    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
    c = itertools.cycle([1, -1])
    ns = map(lambda x: (4 / x) * next(c), ns)
    # step 4: 求和:
    sums = reduce(lambda x, y: x+y, ns)
    return sums

  • 1

Reply