#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import itertools def pi(N): natuals = itertools.count(1, 2) ns = list(itertools.takewhile(lambda x: x < 2 * N, natuals)) ops = itertools.cycle([1, -1]) sum = 0 count = 0 for op in ops: sum += 4 / ns[count] * op count += 1 if count == N: break return sum 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
Nobita