INTRODUCTION

Diagonal is a line segment that connects two vertices but it is not a side.

You can calculate the number of all diagonals in a polygon

You can use the formula $\frac{n(n-3)}{2}$, where n is the number of sides of the polygon.


PYTHON CODE

import math
import matplotlib.pyplot as plt

num_sides = int(input("Enter the number of sides of the polygon: "))
num_diag = int(num_sides * (num_sides - 3) /2)

interior_angle = (num_sides - 2) * 180 / num_sides
diagonal_angle = 180 - interior_angle
diagonal_length = 0.5 / math.cos(math.pi / num_sides)


x_coords = [math.cos(2 * math.pi / num_sides * i) for i in range(num_sides)]
y_coords = [math.sin(2 * math.pi / num_sides * i) for i in range(num_sides)]

fig, ax = plt.subplots()
ax.plot(x_coords, y_coords, 'o-', label='Polygon')
for i in range(num_sides):
    for j in range(i + 2, num_sides):
        ax.plot([x_coords[i], x_coords[j]], [y_coords[i], y_coords[j]], '-', color='gray')
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.set_title(f'Polygon with {num_sides} sides and {num_diag} diagonals')
plt.show()

⬆️⬆️⬆️ See in Google Colaboratory


HOW THE CODE WORKS?

  1. We import the math and matplotlib.pyplot libraries.
  2. The program asks the user to enter the number of sides of the polygon.
  3. If the number of sides is less than 3, the program displays a message that such a polygon does not exist. If the number of sides is 3 or more, the program performs further calculations.
  4. We calculate the number of diagonals of the polygon according to the formulan(n-3)2 and the measure of the interior angle of the polygoninterior_angle.
  5. We calculate the measure of the angle between the diagonalsdiagonal_angle of the polygon and the length of the diagonalsdiagonal_length.
  6. We calculate the coordinates of the polygon’s vertices, draw the polygon and diagonals using the matplotlib library.
  7. The program sets the drawing range and the chart title.
  8. The program displays the graph in the graphics window.