要求
import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.patches import Circle
def circle(w=100,h=100,min_r=5,max_r=10,num=50,):
n = 0
s = 0
p = []
while True:
x = random.uniform(0,w)
y = random.uniform(0,h)
r = random.uniform(min_r,max_r)
if n==0:
p.append([x,y,r])
else:
a =0
for i,c_ in enumerate(p):
c_x = c_[0]
c_y = c_[1]
c_r = c_[2]
l = (x-c_x)**2+(y-c_y)**2-(r+c_r)**2
if l<0:
a+=1
# 当所有l都大于0时
if a ==0:
p.append([x,y,r])
n+=1
if len(p) == num:
break
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim(0,100)
plt.ylim(0,100)
plt.axis(scaled)
plt.axis(equal)
# 轮廓
l_x = [0,0,w,w,0]
l_y = [0,h,h,0,0]
plt.plot(l_x,l_y,r)
# 圆
for i,c_ in enumerate(p):
x = c_[0]
y = c_[1]
r = c_[2]
c = Circle(xy=(x,y),radius=r)
ax.add_patch(c)
s+=np.pi*(r**2)
ratio = (s/(w*h))*100
plt.title("Circle:%d Ratio:%.2f%%"%(num,ratio))
plt.show()
测试代码
circle(100,100,5,10,50)
运行结果