方法一
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()