如何用Python在r1、r2同心圆扇区内均匀生成带宽高的N个随机点
在环形扇区内均匀放置带宽高的点
要实现指定环形扇区内均匀放置带宽高的点,我们可以通过极坐标均匀划分角度和半径区间,再转换为笛卡尔坐标确定每个点的中心位置,最后用可视化工具展示效果。以下是具体的Python实现:
代码实现
import math import matplotlib.pyplot as plt from matplotlib.patches import Rectangle, Wedge def place_points_in_annular_sector(r1, r2, start_angle, end_angle, num_points, point_w, point_h): # 将角度转换为弧度(适配math库计算) start_rad = math.radians(start_angle) end_rad = math.radians(end_angle) angle_range = end_rad - start_rad # 计算角度与半径的步长,取区间中点保证点的均匀分布 angle_step = angle_range / num_points radius_step = (r2 - r1) / num_points point_list = [] for idx in range(num_points): # 取每个角度/半径区间的中点作为点的极坐标参数 current_angle = start_rad + angle_step * (idx + 0.5) current_radius = r1 + radius_step * (idx + 0.5) # 极坐标转笛卡尔坐标,得到点的中心位置 x = current_radius * math.cos(current_angle) y = current_radius * math.sin(current_angle) point_list.append((x, y, point_w, point_h)) return point_list # 自定义参数示例 inner_radius = 2 outer_radius = 5 sector_start = 30 # 扇区起始角度(单位:度) sector_end = 150 # 扇区结束角度(单位:度) total_points = 5 point_width = 0.3 point_height = 0.3 # 获取所有点的坐标与尺寸信息 points = place_points_in_annular_sector(inner_radius, outer_radius, sector_start, sector_end, total_points, point_width, point_height) # 可视化展示效果 fig, ax = plt.subplots(figsize=(8, 8)) ax.set_aspect('equal') # 绘制环形扇区背景 outer_wedge = Wedge((0, 0), outer_radius, sector_start, sector_end, color='#add8e6') inner_wedge = Wedge((0, 0), inner_radius, sector_start, sector_end, color='white') ax.add_patch(outer_wedge) ax.add_patch(inner_wedge) # 绘制每个带宽高的点(用红色矩形表示) for x, y, w, h in points: # 矩形左下角坐标为中心坐标减去宽高的一半 rect = Rectangle((x - w/2, y - h/2), w, h, color='red', edgecolor='black') ax.add_patch(rect) # 设置坐标轴范围,确保完整展示扇区 ax.set_xlim(-outer_radius - 1, outer_radius + 1) ax.set_ylim(-outer_radius - 1, outer_radius + 1) plt.grid(alpha=0.3) plt.title('Uniform Points in Annular Sector') plt.show()
关键说明
- 均匀分布逻辑:将扇区的角度范围和半径范围各自均匀划分为
num_points个区间,取每个区间的中点作为点的极坐标位置,确保点在环形扇区内均匀分布。 - 坐标转换:使用极坐标到笛卡尔坐标的标准转换公式,将极坐标参数转换为平面坐标,方便后续绘制带宽高的矩形点。
- 可视化细节:用
Wedge绘制环形扇区的蓝色背景,用Rectangle绘制带边框的红色矩形点,直观呈现最终效果。
内容的提问来源于stack exchange,提问作者vivek
相关产品推荐
相关产品推荐

