import itertools
def pi(n): s1 = itertools.takewhile(lambda x: x <= 2 n, itertools.count(1, 2)) # 创建奇数序列,取前N项 s2 = sum(map(lambda x: 4 / (x (-1) ** (x // 2)), s1)) # 添加正负号,用4除,求和 return s2
print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok')
Sign in to make a reply
爱电影的小王纸
-- coding:utf-8 --
import itertools
def pi(n): s1 = itertools.takewhile(lambda x: x <= 2 n, itertools.count(1, 2)) # 创建奇数序列,取前N项 s2 = sum(map(lambda x: 4 / (x (-1) ** (x // 2)), s1)) # 添加正负号,用4除,求和 return s2
测试:
print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok')