def pi(N): ' 计算pi的值 ' # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... odds = itertools.count(1,2) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. ns = itertools.takewhile(lambda x: x <= (2 * N -1), odds) # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... pm =list(ns) result = list(map(lambda x: float(4 / x * 1 if pm.index(x) % 2 == 0 else 4 / x * -1), pm)) # step 4: 求和: return sum(result)
学习了
学到了,牛皮
Sign in to make a reply
方大侠百宝箱