'''Fifth experiment with curves, Chapter 14: 
length of a polygonal chain inscribed in the circle

Input:
    n... integer greater than 2

Output:
    plot of a n-sided regular polygon

Typical call of program:
    from python14_5 import polygon
    polygon(8)     # polygon(n)

'''

from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt

def polygon(n):
    
    if not (n <= 2 or type(n) == int):
        raise ValueError('n is not an integer greater than 2')
    plt.figure()
    
    plt.plot([-1.3, 1.3], [0, 0], 'k', [0, 0], [-1.3, 1.3], 'k')
    plt.plot(1.3, 0, 'k>', 0, 1.3,'k^')
    plt.text(1.5, 0, 'x')
    plt.text(0, 1.5, 'y')
    
    t = np.linspace(0, 2*np.pi, 500)
    x, y = np.cos(t), np.sin(t)
    plt.plot(x, y, 'b')
    
    t = np.linspace(0, 2*np.pi, n+1)
    x, y = np.cos(t), np.sin(t)
    plt.plot(x, y, 'r')
    plt.axis('equal')
    
    z = x + 1j*y  #Transform to complex coordinates to calculate distance
    length_of_polygon = sum(abs(z[1:]-z[:-1]))
    
    print('\nnumber of gridpoints:',n)
    print('length of inscribed polygonal chain:',length_of_polygon)
    print('error of approximation:',2*np.pi-length_of_polygon)
       
    plt.show()