用python计算圆周率的平方_用 蒙特卡洛 Monte Carlo 方法 计算圆周率 Π

8c95a6620a82f0f67c25cf3d4898b380.png

在 上图 中, 圆的 半径 为 1, 则 右上角 正方形的 面积 为 1, 右上角 1/4 圆的 面积 为 1/4 Π, 假设 x, y 都 在 [0, 1) 内 均匀随机 取值, 如果 x*x + y*y <=1, 则点 落入 1/4 的圆的范围内, 设 p= 点 x,y 落入 1/4 圆内的 概率, 则有 p=1/4圆的面积 /正方形面积 = 1/4 Π/1, 则有 1/4 Π=p, 也就是 Π=4P, 就是 说, 随机 在 [0, 1) 取值 x,y, 计算 x*x + y*y <=1 的 概率, 再乘以4, 就可以 算出 圆周率的 值。

下边 是 python 程序。
import random
def  compute_pi( ):
   count=0
   incirclecount=0
   divisor=10
   while(1):
       count+=1
       x=random.random( ) 
       y=random.random( )
       if(x*x+y*y<=1):
           incirclecount+=1
       if(count%divisor==0):
           pi=4*incirclecount/count
           print ("n now the loop count %d pi is %f"%(count,pi))
           divisor*=10
           


compute_pi( )

下边是程序运行结果

now the loop count 10 pi is 3.200000

now the loop count 100 pi is 3.280000

now the loop count 1000 pi is 3.084000

now the loop count 10000 pi is 3.144000

now the loop count 100000 pi is 3.142560

now the loop count 1000000 pi is 3.144048

now the loop count 10000000 pi is 3.142086

now the loop count 100000000 pi is 3.141474

可以看出,随着 循环次数的 增加 ,逐渐接近 圆周率,经过 1亿次循环以后, 误差已经在小数点后 4位,也就是小于 1/30000 。 这个方法,是不是很有意思

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值