用matplotlib实现

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. # 支持中文
    4. plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
    5. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
    6. count = 10000
    7. plt.figure(figsize=(11,11)) # 设置画布长宽
    8. a,hits = 5,0 # 设置随机数范围
    9. lsx = [] # 落在圆外的点的列表x
    10. lsy = [] # 落在圆外的点的列表y
    11. lsPx = [] # 落在圆内的点的列表x
    12. lsPy = [] # 落在圆内的点的列表y
    13. for i in range(count):
    14. x,y = np.random.uniform(-a,a),np.random.uniform(-a,a)
    15. pos = (x ** 2 + y ** 2) ** 0.5 # 计算坐标(x,y)到原点的距离
    16. if pos <= 5.0: # 如果距离小于等于5,点在圆内
    17. lsPx.append(x)
    18. lsPy.append(y)
    19. cl = 'red'
    20. else: # 如果距离大于5.0,点在圆外
    21. lsx.append(x)
    22. lsy.append(y)
    23. cl = 'blue'
    24. plt.scatter(lsx,lsy,facecolors='blue') # 绘制散点,落在圆外在点颜色用蓝色
    25. plt.scatter(lsPx,lsPy,facecolors='red') # 绘制散点,落在圆内在点颜色用红色
    26. PI = 4 * len(lsPx) / count # 落在圆内的点数与总数的比值为面积比值,可计算PI值
    27. plt.title('模拟{}次时PI值为{}'.format(count,PI)) # 用算得的PI值做图的标题
    28. plt.show() # 显示绘制结果

    image.png
    turtle实现

    1. import random # 导入随机数库
    2. import turtle # 导入turtle库
    3. n = int(input())
    4. # random.seed(10)
    5. # turtle.tracer(10) 刷新间隔,提高绘制速度
    6. turtle.pensize(4)
    7. turtle.penup()
    8. turtle.goto(-300, -300)
    9. turtle.pendown()
    10. for i in range(4):
    11. turtle.forward(600)
    12. turtle.left(90)
    13. turtle.forward(300)
    14. turtle.pencolor('green')
    15. turtle.circle(300)
    16. hits = 0 # 落在圆内的计数器初值设为 0
    17. for i in range(1, n+1):
    18. x, y = random.random(), random.random() # 生成两个随机数模拟一个点的坐标
    19. signx,signy = random.choice('+-'),random.choice('+-')
    20. # 随机生成x和y的符号“+”或“-”
    21. pos = (x ** 2 + y ** 2)**0.5 # 计算坐标(x,y)到原点的距离
    22. if pos <= 1.0: # 如果距离小于等于1,点在圆内
    23. hits = hits + 1
    24. turtle.pencolor('red') # 落在圆内在点颜色用红色
    25. else: # 如果距离大于1,点在圆外
    26. turtle.pencolor('blue') # 落在圆内在点颜色用蓝色
    27. x = float(signx+str(x)) # 将 x 值与符号拼接并转为浮点数
    28. y = float(signy+str(y)) # 将 y 值与符号拼接并转为浮点数
    29. turtle.penup()
    30. turtle.goto(x * 300, y * 300) # 画笔抬起并移动到数值放大400倍的x,y处
    31. turtle.pendown()
    32. turtle.dot(5) # 画一个半径为 3 的圆点
    33. if i % 10000 == 0: # 实验为10000的倍数次时
    34. turtle.pencolor('black')
    35. pi = 4 * (hits / i) # 根据落在圆内外的点数量估算PI值
    36. turtle.penup() # 画笔抬起
    37. turtle.goto(320, 150- i // 1000 * 30) # 移动到区域外记录当前PI值
    38. turtle.pendown() # 画笔抬起
    39. turtle.write("{}次时PI的值是{:.4f}".format(i,pi),font=("宋体", 18, "normal"))
    40. turtle.update() # 刷新
    41. turtle.hideturtle() # 隐藏光标
    42. turtle.update() # 刷新
    43. turtle.done() # 结束绘制

    TIM截图20200419214406.png