蒙特卡洛圆周率计算

random库是使用随机数的python标准库。

伪随机数:采用梅森旋转算法生产的伪随机数列中元素

random库主要用于生成随机数


基本随机数函数

随机数种子



相同的种子生成的随机数是相同的,可以复现结果。

扩展随机数函数




例 圆周率的计算

蒙特卡洛方法


from random import random
from time import perf_counter
DARTS=1000*1000
hits=0.0
start=perf_counter()
for i in range(1,DARTS+1):
    x,y=random(),random()#对x、y随机撒点
    dist=pow(x**2+y**2,0.5)
    if dist<=1.0:#判断点是否在圆形内
        hits+=1
pi=4*(hits/DARTS)
print("圆周率是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))
圆周率是:3.142116

运行时间是:0.92642s

举一反三

数学思维:找到公式,利用公式求解

计算思维:抽象一种过程,用计算机思维解决

工程应用!!!

猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80657239