# 蒙特卡罗方法计算圆周率
import random
square_count = 0
round_count = 0
loop_time = 1000000
while loop_time:
if loop_time%1000==0:
print(loop_time)
loop_time -= 1
x = random.random() - 0.5
y = random.random() - 0.5
square_count += 1
# 观察是否落入圆中
if(x*x+y*y<=0.25):
round_count += 1
PI_cal = float((round_count / square_count) / 0.25);
print(PI_cal)
结果: