求π
蒙特卡洛法计算π:
通过获得面积比Sy/Sz:让计算机产生很多的随机点(x,y),其中x、y都是[0,1]之间的随机数,可以用判断 是否小于1的方法来确定是否在圆内,则圆内的点数代表圆面积,总点数代表总面积,两者相除就是面积比Sy/Sz。
Python代码展示如下:
from random import random
from math import sqrt
from time import perf_counter
DARTS = 50000000
hits = 0.0
perf_counter()
for i in range(1,DARTS+1):
x,y = random(),random()
dist = sqrt(x**2 + y**2)
if dist <= 1.0:
hits = hits+1
pi = 4 * (hits/DARTS)
#进度条
import time
scale = 50
print('执行开始'.center(scale//2,'-'))
t = time.perf_counter()
for i in range(scale+1):
a = '*' * i
b = '.' * (scale - i)
c = (i/scale) * 100
t -= time.perf_counter()
print('\r{:^3.0f}%[{}->{}]{:.2f}s'.format(c,a,b,-t),\
end='')
time.sleep(0.05)
print('\n'+'执行结束'.center(scale//2,'-'))
#输出结果
print('pi值是{}.'.format(pi))
print('运行时间是:{:.5f}s'.format(perf_counter()))
print('学号后四位:3121')