码迷,mamicode.com
首页 > 其他好文 > 详细

有进度条圆周率计算

时间:2020-03-30 19:53:38      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:蒙特卡罗   image   sleep   dom   class   +=   cal   com   from   

一、用python计算圆周率pi

(1)蒙特卡罗法

技术图片

 1 from random import random
 2 from time import perf_counter
 3 DARTS = 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))

 

(2)公式法

1 pi = 0
2 N = 100
3 for k in range(N):
4      pi += 1/pow(16, k) * (4 / (8 * k + 1) - 2 /(8 * k + 4) - 1/(8 * k + 5) - 1 /(8 * k + 6))
5      print("圆周率值是:{}".format(pi))

二、带进度条

 1 import math
 2 import time
 3 scale=20
 4 t=time.process_time()
 5 for i in range(scale+1):
 6   a,b=***i,..*(scale-i)
 7   c=(i/scale)*100
 8 π=4*(4*math.atan(1/5)-math.atan(1/239))
 9 print("%[{:3}{}->{}]".format(a,b,c))
10 time.sleep(0.1)
11 print(π)
12 print("{:.2f}s".format(t))
13 print("执行结束")

技术图片

技术图片

(改变参数可改变进度条长度)

我没下载IDLE,只能在spyder里运行

有进度条圆周率计算

标签:蒙特卡罗   image   sleep   dom   class   +=   cal   com   from   

原文地址:https://www.cnblogs.com/wendy123/p/12600434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!