Discuss / Python / 作业

作业

Topic source
def pi(N):
    ' 计算pi的值 '
    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...

    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.

    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...

    # step 4: 求和:
    oddNum = itertools.count(1,2)
    ns = itertools.takewhile(lambda x:x <= 2*N, oddNum)
    s = 0
    i = 0
    nsl = list(ns)
    while i < len(nsl) :
        positiveAndNegative = pow(-1,i)
        s = s + positiveAndNegative*4/nsl[i]
        i = i + 1
    return s
print(pi(10))

  • 1

Reply