使用python计算圆周率

Agnes ·
更新时间:2024-09-21
· 830 次阅读

首先构造一个单位正方形和一个四分之一圆,然后随机想其中抛洒大量的点,每个点可能在圆内也可能在圆外,当点数足够多时圆内点将构成圆的面积,全部点将构成矩形面积,用圆内点数量除以全部点数量,就得到了π/4。在这里插入图片描述
上代码:

from time import time from random import random from math import sqrt dates=100000 t1=time() hists=0 for i in range(1,dates): x,y=random(),random() dist=sqrt(x**2+y**2) if dist<=1: hists+=1 pi=4*(hists/dates) print('pi的值是%s'%pi) print('耗时%.8fs'%(time()-t1))

运行结果:
在这里插入图片描述
今天就到这里,拜拜


作者:自律,自爱



用python 圆周率 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号