Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

MA311M Assignment 2 - Code Listing

Animesh Renanse - 180108048


September 2020

1 Question 1
import numpy as np
import matplotlib . pyplot as plt

def Func ( x ) :
assert (x <=5) and (x >= -5) , ’ Out of domain input value . ’
return 1/(1+ x **2)

interpol_pts = [ -5 + (10* i ) /8 for i in range (1 ,9) ]


i nt er po l _v al ue s = [ Func ( x ) for x in interpol_pts ]

class L a g r a n g e I n t e r p o l a t i o n :
def __init__ ( self , x_pts , y_pts ) :

assert len ( x_pts ) == len ( y_pts )


self . x_pts = x_pts
self . y_pts = y_pts
self . n = len ( x_pts ) - 1

def Constru ctBasis ( self , x ) :


L_i = [1 for _ in range ( self . n +1) ]
for i in range ( self . n +1) :

for j in range ( self . n +1) :


if j != i :
L_i [ i ] *= (x - self . x_pts [ j ]) /( self . x_pts [ i ] - self . x_pts [ j
])
return L_i

def CalcInt erpFunc ( self , x ) :


p_n = 0
Basi sFunctio ns = self . Co nstructB asis ( x )
for i in range ( self . n +1) :
p_n += self . y_pts [ i ]* BasisFun ctions [ i ]

return p_n

Interpolator = L a g r a n g e I n t e r p o l a t i o n ( interpol_pts , i n te rp ol _ va lu es )

x = list ( np . linspace ( -3.75 ,5 ,50) )


y = [ Interpolator . C alcInte rpFunc ( p ) for p in x ]

1
plt . plot (x ,y , label = ’ Lagrange Interpolating Function ’)
plt . plot (x ,[ Func ( p ) for p in x ] , label = ’ Actual Function ’)
plt . plot ( interpol_pts , interpol_values , ’o ’)
plt . legend ()
plt . show ()
Listing 1: Question 1 Solution Code

2 Question 2

import numpy as np
import matplotlib . pyplot as plt

def Func ( x ) :
return x +2/ x

class N a t u r a l C u b i c S p l i n e :
def __init__ ( self , x_pts , y_pts ) :

assert len ( x_pts ) == len ( y_pts ) , ’ Bad length inputs . ’


assert ( ( type ( x_pts ) is list ) and ( type ( y_pts ) is list ) ) , ’
Please enter lists only . ’
self . x_pts = x_pts
self . y_pts = y_pts
self . n = len ( x_pts ) - 1 # we assume that we have n +1 points .

def Fit ( self ) :


"""
Solves the n -1 Linear system for Second order derivatives at
the interpolation points , assuming m_0 = m_n = 0.
"""
A = np . zeros ([ self .n -1 , self .n -1])

h = [ self . x_pts [1] - self . x_pts [0] , *[ None for _ in range (1 ,


self . n ) ]] # h [0] is only used for the calculation of u [1]

u = [ None , *[0 for _ in range (1 , self . n ) ]] # values of u are


meaningful from index 1 till n -1.

b = [(6/ h [0]) *( self . y_pts [1] - self . y_pts [0]) , *[ None for _ in
range (1 , self . n ) ]]

v = [] # Would be a vector of length n -1

for i in range (1 , self . n ) :


# Iterate i from 1 to n -1
h_i = self . x_pts [ i +1] - self . x_pts [ i ]
h [ i ] = h_i

u_i = 2*( h [ i ] + h [i -1])


u [ i ] = u_i

b_i = (6/ h_i ) *( self . y_pts [ i +1] - self . y_pts [ i ])


b [ i ] = b_i

v_i = b [ i ] - b [i -1]

2
v . append ( v_i )

# Filling the coeficient matrix A

for i in range ( self .n -1) :


# At row i
if i ==0:
A [0 ,0] = u [1]
A [0 ,1] = h [1]
elif i == self .n -2:
A [i ,i -1] = h [ -2]
A [i , i ] = u [ -1]
else :
A [i ,i -1] = h [ i ]
A [i , i ] = u [ i +1]
print ( i )
A [i , i +1] = h [ i +1]

v = np . array ( v )
m = list ( np . linalg . solve (A , v ) )
m . insert (0 ,0)
m . insert ( -1 ,0)
# # --> Above two are conditions for " Natural " Cubic Splines .
self . m = m
self . h = list ( h )
self . A = A
self . v = list ( v )

def Compile ( self , x ) :


"""
Compiles and makes the function S_i on the basis of m_i ’s and
h_i ’s calculated in S e c o n d D e r i v S o l v e r . This function assumes
that the S e c o n d D e r i v S o l v e r has been executed .
"""
assert (( max ( self . x_pts ) >= x ) and ( min ( self . x_pts ) ) <= x ) , " Given
point is out of domain , MIN = {} , MAX = {} , YOURS = {} " . format (
min ( self . x_pts ) , max ( self . x_pts ) ,x )
# First , determine the interval in which the point x lies in .
if x != min ( self . x_pts ) :
copy_x = self . x_pts . copy ()
copy_x . append ( x )
copy_x = sorted ( copy_x )
i = copy_x . index ( x ) - 1

else :
i =0
print ( " In the Interval : [{} ,{}] " . format ( self . x_pts [ i ] , self .
x_pts [ i +1]) )

# Now let ’s construct the cubic polynomial in this interval .


S_i = ( self . m [ i ]/(6* self . h [ i ]) ) * ( self . x_pts [ i +1] - x ) **3 +
( self . m [ i +1]/(6* self . h [ i ]) ) * (x - self . x_pts [ i ]) **3 + ( self .
y_pts [ i +1]/ self . h [ i ] - ( self . m [ i +1]* self . h [ i ]) /6) *( x - self . x_pts
[ i ]) + ( self . y_pts [ i ]/ self . h [ i ] - ( self . m [ i ]* self . h [ i ]) /6) *(
self . x_pts [ i +1] - x )

return S_i

3
def Calculate ( self , x ) :
self . Fit ()
S_i = self . Compile ( x )
return S_i

x = [1/2 ,1 ,3/2 ,2]


y = list ( Func ( np . array ( x ) ) )

N CS In te r po la to r = N a t u r al C u b i c S p l i n e (x , y )

N CS In te r po la to r . Fit ()

y_new = []
x_new = list ( np . linspace (0.5 ,2 ,100) )
for p in x_new :
y_new . append ( NC S In te rp o la to r . Compile ( p ) )

plt . plot ( x_new , Func ( np . array ( x_new ) ) , label = ’ Actual Function ’)


plt . plot ( x_new , y_new , label = ’ Cubic Spline ’)
plt . plot (x ,y , ’o ’)
plt . legend ()
plt . show ()
Listing 2: Question 2 Solution Code

You might also like