📅  最后修改于: 2023-12-03 15:40:48.426000             🧑  作者: Mango
本文将介绍如何实现一个可以判断多个点是否位于一个圆内的程序。我们会使用Python语言来编写代码,并通过matplotlib库可视化展示结果。
我们要实现的程序应该具备以下功能:
要实现我们的程序,我们需要安装以下依赖:
pip install matplotlib
我们的点坐标数据将从csv文件中读取。假设我们的点数据保存在points.csv
文件中,其中每行数据的格式为x,y
,我们将使用以下代码来读取数据:
import csv
def read_points(filename):
points = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
points.append((float(row[0]), float(row[1])))
return points
points = read_points('points.csv')
现在我们需要实现一个函数来判断指定点是否在圆内。该函数需要接受圆的半径和圆心坐标,以及点的坐标。函数返回值应该是布尔值,表示该点是否在圆内。
def is_point_within_circle(point, center, radius):
return (point[0] - center[0]) ** 2 + (point[1] - center[1]) ** 2 <= radius ** 2
有了上面的两个函数,我们现在可以遍历所有的点,判断它们是否在圆内,并将在圆内的点保存到一个列表中。
def filter_points_within_circle(points, center, radius):
return [point for point in points if is_point_within_circle(point, center, radius)]
filtered_points = filter_points_within_circle(points, (0, 0), 1)
最后,我们需要展示我们的结果。我们将使用matplotlib来绘制图形,并使用不同的颜色区分在和不在圆内的点。
import matplotlib.pyplot as plt
def visualize_points(points, filtered_points, center, radius):
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter([p[0] for p in points], [p[1] for p in points], c='blue', label='Outside circle')
ax.scatter([p[0] for p in filtered_points], [p[1] for p in filtered_points], c='red', label='Inside circle')
ax.set_xlim(center[0] - radius - 1, center[0] + radius + 1)
ax.set_ylim(center[1] - radius - 1, center[1] + radius + 1)
ax.add_patch(plt.Circle(center, radius, fill=False))
ax.legend(loc='upper right')
plt.show()
visualize_points(points, filtered_points, (0, 0), 1)
import csv
import matplotlib.pyplot as plt
def read_points(filename):
points = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
points.append((float(row[0]), float(row[1])))
return points
def is_point_within_circle(point, center, radius):
return (point[0] - center[0]) ** 2 + (point[1] - center[1]) ** 2 <= radius ** 2
def filter_points_within_circle(points, center, radius):
return [point for point in points if is_point_within_circle(point, center, radius)]
def visualize_points(points, filtered_points, center, radius):
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter([p[0] for p in points], [p[1] for p in points], c='blue', label='Outside circle')
ax.scatter([p[0] for p in filtered_points], [p[1] for p in filtered_points], c='red', label='Inside circle')
ax.set_xlim(center[0] - radius - 1, center[0] + radius + 1)
ax.set_ylim(center[1] - radius - 1, center[1] + radius + 1)
ax.add_patch(plt.Circle(center, radius, fill=False))
ax.legend(loc='upper right')
plt.show()
points = read_points('points.csv')
filtered_points = filter_points_within_circle(points, (0, 0), 1)
visualize_points(points, filtered_points, (0, 0), 1)
上面的代码中,我们用到了csv、numpy、matplotlib等常用库。projec文件的文件命名或点的坐标存放位置,都需要根据具体实现进行修改。
运行结果可见:
到这里,我们的程序实现就完成了。我们可以看到所有在圆内的点都被正确识别出来,并且被用红色圆点标记出来了。