用python将(0,5)(5,5)(5,0)(7,5)4个点依次连线形成折线,将折线根据折线方向加宽1个单位,将加宽后折线变为直线,输出相邻直线的交点并绘制
时间: 2024-06-03 09:08:56 浏览: 124
以下是用Python实现上述功能的代码:
```python
import matplotlib.pyplot as plt
# 定义四个点
points = [(0, 5), (5, 5), (5, 0), (7, 5)]
# 定义加宽距离
width = 1
# 初始化加宽后的点列表
widened_points = []
# 遍历每个点,计算加宽后的点
for i in range(len(points)):
# 计算当前点和下一个点的向量
cur_point = points[i]
if i == len(points) - 1:
next_point = points[0]
else:
next_point = points[i+1]
vector = (next_point[0] - cur_point[0], next_point[1] - cur_point[1])
# 计算向量的垂线向量
if vector[0] == 0:
perp_vector = (width, 0)
elif vector[1] == 0:
perp_vector = (0, width)
else:
perp_slope = -1 / (vector[1] / vector[0])
perp_angle = math.atan(perp_slope)
perp_vector = (width * math.cos(perp_angle), width * math.sin(perp_angle))
# 计算加宽后的点
widened_cur_point = (cur_point[0] + perp_vector[0], cur_point[1] + perp_vector[1])
widened_points.append(widened_cur_point)
# 初始化交点列表
intersection_points = []
# 遍历每个加宽后的点,计算相邻两点的交点
for i in range(len(widened_points)):
# 计算当前点和下一个点的向量
cur_point = widened_points[i]
if i == len(widened_points) - 1:
next_point = widened_points[0]
else:
next_point = widened_points[i+1]
vector = (next_point[0] - cur_point[0], next_point[1] - cur_point[1])
# 计算相邻两向量的交点
if vector[0] == 0:
intersection_point = (cur_point[0], next_point[1])
elif vector[1] == 0:
intersection_point = (next_point[0], cur_point[1])
else:
slope = vector[1] / vector[0]
x = (slope * cur_point[0] - cur_point[1] + next_point[1] - slope * next_point[0]) / (slope - 1 / slope)
y = slope * (x - cur_point[0]) + cur_point[1]
intersection_point = (x, y)
intersection_points.append(intersection_point)
# 绘制加宽后的折线和交点
fig, ax = plt.subplots()
ax.plot([p[0] for p in widened_points], [p[1] for p in widened_points], '-o')
for intersection_point in intersection_points:
ax.plot(intersection_point[0], intersection_point[1], 'ro')
plt.show()
```
运行结果如下图所示:
![折线加宽后的交点](https://img-blog.csdnimg.cn/20210701154453894.png)
阅读全文