# -*- coding: utf-8 -*-
"""
Spyder Editor

Lab 5, Q2
"""

import numpy as np
import matplotlib.pyplot as plt

def polyx(a,x):
    # evaluates a polynomial f(x) of x,
    # given a nump array of coefficients a,
    # such that 
    # 
    # f(x) = a[0] + a[1]x + a[2]x**2 + ... + a[n-1]x**(n-1)
    
    f = 0
    for i in range(len(a)):
        f = f + a[i]*x**i
        
    return f

def lagx(j,x,xp):
    # creates the jth Lagrange polynomial with node points
    # given by the set xp, evaluated at x.

    Lx = np.zeros(len(x))
    num,den = 1,1
    for i in range(len(xp)):
        if i!=j:
            num = num*(x-xp[i])
            den = den*(xp[j]-xp[i])
            
    Lx = num/den
    return Lx    
    
#set up point pairs for interpolation
xp = np.array([[-1],[0],[1],[2]])
yp = np.array([[2],[-1],[1],[0]])

x = np.linspace(-1.5,2.5,100)

f = 0.*x
for j in range(len(xp)):
    Lxj = lagx(j,x,xp)
    
    f = f + yp[j]*Lxj
    plt.plot(x,f)
    
    
plt.plot(x,f)






