Discuss / Python / 我多能想到的效率更高的代码需要for循环

我多能想到的效率更高的代码需要for循环

Topic source

青铜神裔

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

这里只是不想用for循环,效率上其实并不高

import itertools


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, ...
    d = map(lambda x: 4/x*(-1)**(x//2), ns)
    # step 4: 求和:
    return sum(d)

# 测试:
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')
 4/x*(-1)**(x//2)

这一行 看不懂啥意思

(x//2)是判断是单数还是双数,再用次数乘以-1,这样就是间隔得正副正副形式,最后得到结果


  • 1

Reply