Discuss / Python / 作业

作业

Topic source

#1 Created at ... [Delete] [Delete and Lock User]

from functools import reduce

import itertools

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: 求和:

    '''

    odd = itertools.count(1)

    iter = itertools.takewhile(lambda x:x < N, odd)

    li1 = filter(lambda x: x %2 ==1 , iter)

    li2 = map(lambda x : 4/x if (x//2)%2==0 else -4/x, li1)

    result = reduce(lambda x,y: x+y, li2)

    return result

# 测试:

print(pi(10))

print(pi(100))

print(pi(1000))

print(pi(10000))

assert 3.3 < pi(10) < 3.4

assert 3.12 < pi(100) < 3.13

assert 3.13 < pi(1000) < 3.14

assert 3.1413 < pi(10000) < 3.1415

print('ok')


  • 1

Reply