【Python学习】蒙特卡洛方法产生pi的值

方法一

import random
import math
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
num = 0
x_set1 = []
y_set1 = []
x_set2 = []
y_set2 = []
for i in range(100000):
    x = random.randint(1,20)/10
    y = random.randint(1,20)/10
    d = math.sqrt(math.pow(x-1,2)+math.pow(y-1,2))
    if d<=1:
        num+=1
        x_set1.append(x)
        y_set1.append(y)
    else:
        x_set2.append(x)
        y_set2.append(y)
pi_value = 4*num/100000
x_set1 = np.array(x_set1)
y_set1 = np.array(y_set1)
x_set2 = np.array(x_set2)
y_set2 = np.array(y_set2)
fig = plt.figure() 
axes = fig.add_subplot(111) 
axes.plot(x_set1,y_set1,'r.',markersize = 1)
axes.plot(x_set2,y_set2,'b.',markersize = 1)
plt.axis('equal') # 防止图像变形
circle = Circle(xy=(1,1), radius=1, alpha=0.5)
axes.add_patch(circle)
plt.show()

方法二

x= np.random.rand(10000)*2
y= np.random.rand(10000)*2
d = np.sqrt(np.power(x-1,2)+np.power(y-1,2))
num = sum(d<=1)
pi_value = 4*num/10000
fig = plt.figure() 
axes = fig.add_subplot(111) 
axes.plot(x, y,'ro',markersize = 1)
plt.axis('equal') # 防止图像变形
circle = Circle(xy=(1,1), radius=1, alpha=0.5)
axes.add_patch(circle)
plt.show()

方法三

num = 0
fig = plt.figure() 
axes = fig.add_subplot(111) 
for i in range(10000):
    x = random.randint(1,20)/10
    y = random.randint(1,20)/10
    d = math.sqrt(math.pow(x-1,2)+math.pow(y-1,2))
    if d<=1:
        num+=1
        axes.plot(x,y,'r.',markersize = 1)
    else:
        axes.plot(x,y,'b.',markersize = 1)
pi_value = 4*num/10000
plt.axis('equal') # 防止图像变形
circle = Circle(xy=(1,1), radius=1, alpha=0.5)
axes.add_patch(circle)
plt.show()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值