Python学习六

2.用蒙特卡罗法计算π的值。
蒙特卡罗法:基于“随机数”的算法,通过计算落在单位圆内的点与落在正方形内的 点的比值求PI。

 

 
                            蒙特卡罗法
from random import random
from math import sqrt

max = 2000000
count = 0
for i in range (1,max):
    x, y = random(),random()
    dist = sqrt(x**2+y**2)
    if dist <= 1:
        count = count + 1
pi = 4*(count/max)
print("π的值为%f"%pi)

  

 
posted @ 2020-02-05 20:33  #魂  阅读(95)  评论(0编辑  收藏  举报