Professional Documents
Culture Documents
MA311M Assignment 2 - Code Listing: Animesh Renanse - 180108048 September 2020
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)
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 ) :
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 )
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 ) :
b = [(6/ h [0]) *( self . y_pts [1] - self . y_pts [0]) , *[ None for _ in
range (1 , self . n ) ]]
v_i = b [ i ] - b [i -1]
2
v . append ( v_i )
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 )
else :
i =0
print ( " In the Interval : [{} ,{}] " . format ( self . x_pts [ i ] , self .
x_pts [ i +1]) )
return S_i
3
def Calculate ( self , x ) :
self . Fit ()
S_i = self . Compile ( x )
return S_i
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 ) )