python随机生成数字(python产生10000个随机点计算圆周率)

2022-08-27 14:15:52
摘要:  python随机生成数字(python产生10000个随机点计算圆周率)...

蒙特卡洛法求圆周率,通过多次撒点,模拟概率,求面积,而是否在圆内,可以通过到圆心的距离求解,利用计算机的运算速度,可以很快求出圆周率。撒点次数越多,圆周率就越准确。代码如下:

from random import random

from math import sqrt

from time import process_time

DARTS=10000

hits=0.0

process_time()

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)

print("PI值是{}.".format(pi))

print("运行时间是:{:.5f}s".format(process_time()))