You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码实现随机圆的多随机点生成及对应圆绘制?

生成指定数量的圆形内随机点并绘图

直接上修改后的完整代码,包含批量生成随机点和绘图功能:

import random
import math
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def generate_random_point_in_circle(circle_x, circle_y, circle_r):
    # 生成随机角度
    alpha = 2 * math.pi * random.random()
    # 生成随机半径(用sqrt保证点在圆内均匀分布)
    r = circle_r * math.sqrt(random.random())
    # 计算坐标
    x = r * math.cos(alpha) + circle_x
    y = r * math.sin(alpha) + circle_y
    return (x, y)

# 圆的参数
circle_r = 10
circle_x = 5
circle_y = 7

# 获取用户输入的点数量
point_count = int(input("请输入随机点数量:"))

# 生成指定数量的随机点
points = [generate_random_point_in_circle(circle_x, circle_y, circle_r) for _ in range(point_count)]

# 打印所有点的坐标
print("生成的随机点坐标:")
for idx, (x, y) in enumerate(points, 1):
    print(f"点{idx}: ({x:.2f}, {y:.2f})")

# 绘图部分
fig, ax = plt.subplots()
# 绘制圆
circle = Circle((circle_x, circle_y), circle_r, fill=False, color='blue', label='圆')
ax.add_patch(circle)
# 绘制随机点
x_coords = [p[0] for p in points]
y_coords = [p[1] for p in points]
ax.scatter(x_coords, y_coords, color='red', s=10, label='随机点')
# 设置坐标轴比例一致,避免圆变形
ax.set_aspect('equal')
# 设置坐标轴范围
ax.set_xlim(circle_x - circle_r - 1, circle_x + circle_r + 1)
ax.set_ylim(circle_y - circle_r - 1, circle_y + circle_r + 1)
# 添加图例和标题
plt.legend()
plt.title(f"圆内{point_count}个随机点分布")
plt.show()

关键修改说明

  • 把单个点的生成逻辑封装成函数,方便重复调用
  • 用列表推导式循环指定次数,批量生成所有随机点
  • 加入用户输入功能,直接指定要生成的点数量
  • 新增绘图模块:用matplotlib绘制圆和所有随机点,同时调整坐标轴比例避免圆变形

补充:代码里用math.sqrt(random.random())而非直接乘random.random(),是为了避免点集中在圆心附近,开平方后能让点在圆内均匀分布。

内容的提问来源于stack exchange,提问作者Niki Sedlarević

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:55:22