"""
Problem 3
"""

import numpy as np
from scipy.special import roots_legendre
from matplotlib import pyplot as plt


np.set_printoptions(precision=2)
ANS = 2*np.pi/3


def f(phi, z):
    return (z*np.sin(phi))**2


def sphere_integrate(func, m):
    phi_j = np.linspace(0, 2*np.pi, 2*m)
    z_i, w_i = roots_legendre(m)
    PHI, Z = np.meshgrid(phi_j, z_i)
    W = np.tile(w_i, (2*m, 1)).T
    return (np.pi/m)*np.sum(W * func(PHI, Z))


def test_sphere():
    m_vals = np.geomspace(3, 1000, dtype='i')
    I_vals = np.array([sphere_integrate(f, m) for m in m_vals])
    plt.figure()
    plt.subplot(111, xlabel=r'$m$ (number of points in $\theta$)', ylabel='Absolute error', xscale='log', yscale='log')
    plt.plot(m_vals, np.abs(I_vals - ANS))
    plt.show()


if __name__ == '__main__':
    print('COMMIT!!!')
    test_sphere()
