用matplotlib实现
import matplotlib.pyplot as plt
import numpy as np
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
count = 10000
plt.figure(figsize=(11,11)) # 设置画布长宽
a,hits = 5,0 # 设置随机数范围
lsx = [] # 落在圆外的点的列表x
lsy = [] # 落在圆外的点的列表y
lsPx = [] # 落在圆内的点的列表x
lsPy = [] # 落在圆内的点的列表y
for i in range(count):
x,y = np.random.uniform(-a,a),np.random.uniform(-a,a)
pos = (x ** 2 + y ** 2) ** 0.5 # 计算坐标(x,y)到原点的距离
if pos <= 5.0: # 如果距离小于等于5,点在圆内
lsPx.append(x)
lsPy.append(y)
cl = 'red'
else: # 如果距离大于5.0,点在圆外
lsx.append(x)
lsy.append(y)
cl = 'blue'
plt.scatter(lsx,lsy,facecolors='blue') # 绘制散点,落在圆外在点颜色用蓝色
plt.scatter(lsPx,lsPy,facecolors='red') # 绘制散点,落在圆内在点颜色用红色
PI = 4 * len(lsPx) / count # 落在圆内的点数与总数的比值为面积比值,可计算PI值
plt.title('模拟{}次时PI值为{}'.format(count,PI)) # 用算得的PI值做图的标题
plt.show() # 显示绘制结果
turtle实现
import random # 导入随机数库
import turtle # 导入turtle库
n = int(input())
# random.seed(10)
# turtle.tracer(10) 刷新间隔,提高绘制速度
turtle.pensize(4)
turtle.penup()
turtle.goto(-300, -300)
turtle.pendown()
for i in range(4):
turtle.forward(600)
turtle.left(90)
turtle.forward(300)
turtle.pencolor('green')
turtle.circle(300)
hits = 0 # 落在圆内的计数器初值设为 0
for i in range(1, n+1):
x, y = random.random(), random.random() # 生成两个随机数模拟一个点的坐标
signx,signy = random.choice('+-'),random.choice('+-')
# 随机生成x和y的符号“+”或“-”
pos = (x ** 2 + y ** 2)**0.5 # 计算坐标(x,y)到原点的距离
if pos <= 1.0: # 如果距离小于等于1,点在圆内
hits = hits + 1
turtle.pencolor('red') # 落在圆内在点颜色用红色
else: # 如果距离大于1,点在圆外
turtle.pencolor('blue') # 落在圆内在点颜色用蓝色
x = float(signx+str(x)) # 将 x 值与符号拼接并转为浮点数
y = float(signy+str(y)) # 将 y 值与符号拼接并转为浮点数
turtle.penup()
turtle.goto(x * 300, y * 300) # 画笔抬起并移动到数值放大400倍的x,y处
turtle.pendown()
turtle.dot(5) # 画一个半径为 3 的圆点
if i % 10000 == 0: # 实验为10000的倍数次时
turtle.pencolor('black')
pi = 4 * (hits / i) # 根据落在圆内外的点数量估算PI值
turtle.penup() # 画笔抬起
turtle.goto(320, 150- i // 1000 * 30) # 移动到区域外记录当前PI值
turtle.pendown() # 画笔抬起
turtle.write("{}次时PI的值是{:.4f}".format(i,pi),font=("宋体", 18, "normal"))
turtle.update() # 刷新
turtle.hideturtle() # 隐藏光标
turtle.update() # 刷新
turtle.done() # 结束绘制