def pi(N):
#' 计算pi的值 '
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
count=itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
count=itertools.takewhile(lambda x:x<=(2*N-1),count)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
def trans(x):
if (x-1)/2 %2 !=0:
x=-x
return 4/x
# step 4: 求和:
return reduce(lambda x1,x2:x1+x2,map(trans,count))
Sign in to make a reply
这样的话17422
def pi(N):
#' 计算pi的值 '
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
count=itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
count=itertools.takewhile(lambda x:x<=(2*N-1),count)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
def trans(x):
if (x-1)/2 %2 !=0:
x=-x
return 4/x
# step 4: 求和:
return reduce(lambda x1,x2:x1+x2,map(trans,count))