#!/usr/bin/env python
# Program to plot polygons and circles
# Requires the matplotlib plotting library
# We need some math functions
from math import cos, sin, pi
# Matplotlib is a plotting library for python
from matplotlib import pyplot
def generate_polygon(N, R_min, O = [0.0,0.0]):
# Function which generates the set of points to draw a N-sided polygon
# with smallest radius R_min, centered at O (default is [0,0])
# These lists will hold the x and y coords of the corners of the polygon
X = []
Y = []
# R_max is the largest radius of the polygon
R_max = R_min / cos(pi/N)
# Looping over the number of corners, adding the coordinates to
# the lists X and Y. Going to N+1 because we need the first point
# to be the same as the last for the figure to be closed
for n in xrange(N+1):
X.append(O[0] + R_max * sin(n*2*pi / N))
Y.append(O[1] + R_max * cos(n*2*pi / N))
# Returning the lists of coordinates, as well as R_max to be used
# as R_min for the next polygon
return X, Y, R_max
def generate_circle(R, O = [0.0, 0,0]):
# Function to draw circle. A circle is really nothing other than
# a polygon with loads and loads of sides, so we reuse
# generate_polygon to save some writing
# Number of sides in the 'circle'
N = 5000
# Generating points to draw the circle
X, Y, R_max = generate_polygon(N, R, O)
# Returning the list of points, but not the new radius
# since R_min and R_max are the same for a circle
return X, Y
def main():
# It is customary, but not neccessary, to put the main body of a program
# in a function called main()
# Radius of the first circle is 1
R = 1
# Largest polygon is 100 sided. Change to anything you want,
# though due to limited resolution in the plot there is not much
# to be seen beyond 100
N_max = 100
# Looping from a triangle up to a N_max-sided polygon.
for N in xrange(3, N_max):
# Drawing a circle with the plot() function from pyplot
X, Y = generate_circle(R)
pyplot.plot(X, Y)
# Drawing a polygon
X, Y, R = generate_polygon(N, R)
pyplot.plot(X, Y)
# Setting equal scale on the x and y axis
pyplot.axis('equal')
# Saving figure as a png
pyplot.savefig('polygons.png')
# This is a customary construction that only runs the main() function
# if the program is run from the command line.
# If the program is run from the command line, the internal name of the program
# will be '__main__', and the function main() will be executed
# If the program is imported as a module, to use the functions in another
# program, the name will be something else, and the function will not run
if __name__ == '__main__':
main()