Discuss / Python / 交作业

交作业

Topic source

lldhsds

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

交作业

import itertoolsdef pi(N):    ' 计算pi的值 '    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...    odd_numbers = itertools.count(start=1, step=2)    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.    odd_numbers_n = list(itertools.islice(odd_numbers, N))    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...    result = [((-1) ** i) * 4 / num  for i, num in enumerate(odd_numbers_n)]    # step 4: 求和:    return sum(result)# 测试:print(pi(10))print(pi(100))print(pi(1000))print(pi(10000))assert 3.04 < pi(10) < 3.05assert 3.13 < pi(100) < 3.14assert 3.140 < pi(1000) < 3.141assert 3.1414 < pi(10000) < 3.1415print('ok')

  • 1

Reply