利用蒙特卡罗法算PI,并绘制曲线图和散点图

原理 落在圆内的概率=圆与正方形面积之比=0.25Π

先上图

在这里插入图片描述

绘制折线图

import random
import matplotlib.pyplot as plt
#原理  落在圆内的概率=圆与正方形面积之比=0.25Π
# total指代在圆里面晒的豆子数
def pi(total):
    count = 0
    for i in range(total):
        x = random.random()
        y = random.random()
        x = pow(x, 2)
        y = pow(y, 2)
        dis = pow(x + y, 0.5)
        if dis <= 1:
            count += 1
    pi = 4 * count / total
    print(total,"π是", 4 * count / total)
    return  pi
with open("pi.txt10","w") as f:
    i=500
    xx=[]
    yy=[]
    for x in range(i):
        if x!=0:
           y1=pi(x)
           xx.append(x)
           yy.append(y1)
           f.write("当total为0{},π为{}\n".format(x,y1))
    plt.plot(xx,yy,linestyle=':', linewidth=1, markersize=10)
    plt.show()

当total=500

在这里插入图片描述

当total=1000

在这里插入图片描述

当total=10000

在这里插入图片描述

绘制散点图

import random

import matplotlib.pyplot as plt
import pandas as pd

def pi(total):
    x1=[]
    y1=[]
    x2=[]
    y2=[]
    count = 0
    for i in range(total):
        x = random.random()
        y = random.random()
        dis = pow(pow(x, 2) + pow(y, 2), 0.5)
        if dis <= 1:
            x1.append(x)
            y1.append(y)
            count += 1
        else:
            x2.append(x)
            y2.append(y)
    pi = 4 * count / total
    print(total,"π是", 4 * count / total)
    return  pi,x1,y1,x2,y2






#定义颜色变量
color = ['c', 'b', 'g', 'r', 'm', 'y', 'k', 'w']
total=5000
PI,x1,y1,x2,y2=pi(total)
#画图

fig=plt.figure(figsize=(6,6))#设置画布大小
rect1 = [0.10, 0.1, 0.8, 0.8]#后两个数根据画布比例设置宽和高
ax1 = plt.axes(rect1)
plt.scatter(x1, y1,s=1, c=color[0])#s调整点的大小
plt.scatter(x2, y2,s=1, c=color[2])
plt.title(PI)
plt.xlabel(total)
plt.show()

total=3000

在这里插入图片描述

total=100000

在这里插入图片描述

total=1000000

在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值