import numpy as np, matplotlib.pyplot as plt
NUM_INTERPOL_POINTS = 5


def heaviside(x, a=-1):
    if x <= 1:
        return 0
    return 1

def evaluer_polynom(coeff_list,x):
    degree = len(coeff_list)-1
    value = 0
    for i in range(degree+1):
        value += coeff_list[degree-i] * (x**i)
    return value

def gen_chevbyesky_ekstremalgitter(n, a = 0, b = 0):
    x_points = np.zeros(n)

    #fordi range kjører for 0 ≤ i ≤ (n-1)
    #men vi vil ha 0 ≤ i ≤ n
    n = n-1
    for i in range(n+1):
        x_points[i] = np.cos(np.pi*i/(n))

    if a or b:
        x_points = a + (b-a)*((x_points+1)/2)

    return x_points

def oppg3():
    x_akse = np.linspace(0,np.pi, 100)
    heavi_y = [heaviside(x) for x in x_akse]

    interpol_x = np.linspace(0,np.pi,NUM_INTERPOL_POINTS)
    interpol_y = [heaviside(x) for x in interpol_x]

    coeff = np.polyfit(interpol_x,interpol_y,NUM_INTERPOL_POINTS-1)

    polynom_y = [evaluer_polynom(coeff, x) for x in x_akse]

    plt.plot(x_akse,heavi_y)
    plt.plot(x_akse,polynom_y)
    plt.scatter(interpol_x,interpol_y)

def oppg4():
    x_akse = np.linspace(0, np.pi, 100)
    heavi_y = [heaviside(x) for x in x_akse]

    interpol_x = gen_chevbyesky_ekstremalgitter(NUM_INTERPOL_POINTS, a=0, b=np.pi)
    interpol_y = [heaviside(x) for x in interpol_x]

    coeff = np.polyfit(interpol_x, interpol_y, NUM_INTERPOL_POINTS - 1)

    polynom_y = [evaluer_polynom(coeff, x) for x in x_akse]

    plt.plot(x_akse, heavi_y)
    plt.plot(x_akse, polynom_y)
    plt.scatter(interpol_x,interpol_y)
    plt.show()

oppg3()
oppg4()