这里附上圆周率的计算公式:
1 import time 2 3 def Countpi(N = 100): 4 pi = 0.0 5 k = 0 6 start = time.perf_counter() 7 for i in range(N): 8 pi += 1 / pow(16, i) * ( 9 4/(8*i + 1) - 2/(8*i 10 + 4) - 1/(8*i + 5) - 1/(8*i + 6)) 11 if i % 2 == 0: 12 k += 1 13 Progress(i, start, pi, k) 14 return pi 15 16 def Progress(i, start, pi, k, L = 50): 17 a = '*' * k 18 b = '.' * (L - k) 19 c = (k/L) * 100 20 dur = time.perf_counter() - start 21 print(' {:^3.0f}%[{}->{}]计算时间为: {:.2f}s'.format(c, a, b, dur), end='') 22 time.sleep(0.1) 23 24 def main(): 25 print('圆周率计算开始'.center(50, '-')) 26 pi = Countpi() 27 print(' '+'圆周率计算结束'.center(50, '-')) 28 print('圆周率计算得: {}'.format(pi)) 29 30 main()
结果就是这样啦:
其实还有一种蒙特卡罗方法可以计算圆周率, 它是通过在这个正方形内部,随机产生10000个点(即10000个坐标对 (x, y)),计算它们与中心点的距离,从而判断是否落在圆的内部。如果这些点均匀分布,那么圆内的点应该占到所有点的 π/4,因此将这个比值乘以4,就是π的值。
下面就直接附上这种方法的源码(不过没有进度条) :
1 from random import random 2 from time import perf_counter 3 DARTS = 1000*1000 4 hits = 0.0 5 start = perf_counter() 6 for i in range(1, DARTS+1): 7 x, y = random(), random() 8 dist = pow(x ** 2 + y ** 2, 0.5) 9 if dist <= 1.0: 10 hits = hits + 1 11 pi = 4 * (hits/DARTS) 12 print("圆周率值是: {}".format(pi)) 13 print("运行时间是: {:.5f}s".format(perf_counter() - start))