#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep  3 14:16:35 2024

@author: sam
"""

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1,2)



def polyx(a,x):
    f = 0
    for i in range(len(a)):
        f += a[i]*(x)**i
    return f
    

'''a)'''

xp = np.array([[-1],[0],[1],[2]]) #define x values of function we want to interpolate
yp = np.array([[2],[-1],[1],[0]]) #define according y values



'''b)'''

V = np.hstack([xp**0]) #create vector V with just 1's
for i in range(1,len(xp)): #loop from 1 to the length of xp vector
    V = np.hstack([V,xp**i]) #add xp with exponent i to matrix V



'''c)'''

VI = np.linalg.inv(V) #inverts matrix V

A = np.matmul(VI,yp) #matrix multiplies V inverse with yp values



'''d)'''

f = polyx(A,x)

plt.plot(x,f) #plots interpolated function