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)