Week 11: Homework Solutions

4.

"""
Plotting 20 random stars
"""

import random
import numpy as np
import matplotlib.pyplot as plt


def draw_star(centre, radius, n, ratio):
    """
    Draw a star with specified centre, radius, number of
    points and ratio of outside to inside circle.
    The idea is that as we go round we alternate plotting a point
    on an outside circle, of radius 'radius', and a point on 
    an inside circle, of radius 'radius/ratio'.
    """
    theta = np.linspace(0, 2*np.pi, 2*n+1)
    r = np.zeros(2*n+1)
    for i in range(2*n+1):
        if i % 2 == 0:
            r[i] = radius
        else:
            r[i] = radius/ratio
    plt.plot(r*np.cos(theta) + centre[0],
             r*np.sin(theta) + centre[1],
             color="red")

for i in range(20):
    # plot a random star where coordinates of the centre
    # are in the interval [0, 30], the radius is in [1, 4],
    # number of points is in {4, 5, ..., 16} and ratio is in [1.8, 4.8]
    draw_star([30*random.random(), 30*random.random()],
              3*random.random() + 1,
              random.randrange(4, 16),
              3*random.random() + 1.8)

plt.axes().set_aspect("equal")
plt.axis('off')
plt.savefig("stars.png")
plt.show()