#!/usr/bin/env python
# coding: utf-8

# In[1]:


from numpy import array
x = array([-2, -1, 0, 1, 3])
y = array([9, -1, -3, -3, -5])
n = len(x)


# In[5]:


from numpy import polyfit, polyval
p = polyfit(x, y, n-1) #coefficients of interpolating polynomial


# In[4]:


p


# In[6]:


polyval(p, 2) #value of polynomial at 2


# In[8]:


from numpy import zeros
A = zeros((n, n))
A[:, n-1] = 1
for i in range(n-1):
    A[:, i] = x ** (n-1-i)


# In[9]:


A #Vandermonde matrix


# In[11]:


from numpy.linalg import solve
c = solve(A, y)


# In[12]:


polyval(c, 2)


# In[14]:


from numpy import interp
interp(2, x, y) #value of linear spline at x=2


# In[2]:


from scipy.interpolate import CubicSpline
S = CubicSpline(x, y) #boundary conditions: not-a-knot


# In[7]:


S.c #coefficients of each cubic piece


# In[3]:


S(2) #value at x=2


# In[10]:


from numpy import linspace
xp = linspace(x[0], x[n-1], 100)
yp = S(xp)


# In[19]:


#plot points with their cubic spline interpolation
from matplotlib.pyplot import plot
plot(x, y, 's')
plot(xp, yp)


# In[21]:


#plot points with their polynomial interpolation
yp = polyval(c, xp)
plot(x, y, 's')
plot(xp, yp)


# In[8]:


Sn = CubicSpline(x, y, bc_type='natural') #natural boundary conditions


# In[9]:


Sn(2)


# In[11]:


ypn = Sn(xp)


# In[14]:


from matplotlib.pyplot import plot, legend
plot(x, y, 's', label='given points')
plot(xp, yp, label='not-a-knot')
plot(xp, ypn, label='natural')
legend()


# In[ ]:




