在矩形框内生成随机圆

要求

  • 圆不能重合
  • 圆形面积占比大于60%
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)

运行结果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值