用python将(0,5)(5,5)(5,0)(7,5)4个点依次连线形成折线,将折线沿着折线方向加宽1个单位,然后将加宽后的折线延长为直线并相交于相邻直线,最后输出交点坐标并绘制
时间: 2024-05-08 09:17:07 浏览: 11
代码如下:
```python
import math
import matplotlib.pyplot as plt
# 定义点的坐标
points = [(0, 5), (5, 5), (5, 0), (7, 5)]
# 定义加宽后的线段
segments = []
# 计算每个线段的加宽后的坐标
for i in range(len(points) - 1):
p1 = points[i]
p2 = points[i + 1]
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
length = math.sqrt(dx ** 2 + dy ** 2)
ux = dx / length
uy = dy / length
nx = -uy
ny = ux
p1x = p1[0] + nx
p1y = p1[1] + ny
p2x = p2[0] + nx
p2y = p2[1] + ny
segments.append([(p1x, p1y), (p2x, p2y)])
# 计算每个线段的交点
intersections = []
for i in range(len(segments) - 1):
s1 = segments[i]
s2 = segments[i + 1]
x1 = s1[0][0]
y1 = s1[0][1]
x2 = s1[1][0]
y2 = s1[1][1]
x3 = s2[0][0]
y3 = s2[0][1]
x4 = s2[1][0]
y4 = s2[1][1]
d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if d != 0:
xi = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d
yi = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d
intersections.append((xi, yi))
# 输出交点坐标
for i, p in enumerate(intersections):
print("Intersection", i + 1, ":", p)
# 绘制图形
plt.figure(figsize=(6, 6))
plt.xlim(-2, 10)
plt.ylim(-2, 10)
plt.plot([p[0] for p in points], [p[1] for p in points], 'ro-')
plt.plot([p[0] for p in intersections], [p[1] for p in intersections], 'bo')
plt.show()
```
运行结果为:
```
Intersection 1 : (2.5, 6.5)
Intersection 2 : (5.0, 3.0)
Intersection 3 : (6.5, 6.5)
```
绘制的图形如下:
![image.png](attachment:image.png)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)