"""
Problem 4
"""

import numpy as np


s_inf = np.pi/4


def term(n):
    return (-1) ** n / (2 * n + 1)


def basic_sum(tol):
    n = 0
    val = 0
    while True:
        val += term(n)
        if np.abs(s_inf - val) < tol:
            return val, n
        n += 1


def aitkin_sum(tol):
    n = 0
    while True:
        sn2 = np.sum(term(np.arange(0, n+3)))
        sn1 = sn2 - term(n+2)
        sn0 = sn1 - term(n+1)
        s_aitkin = sn0 - (sn1 - sn0)**2 / (sn2 - 2*sn1 + sn0)
        if np.abs(s_inf - s_aitkin) < tol:
            return s_aitkin, n
        n += 1


if __name__ == '__main__':
    print(basic_sum(1e-7))
    print(aitkin_sum(1e-7))

