""" Interpolation de Lagrange """
import numpy as np
import matplotlib.pyplot as plt
######## Exercice 1: ########
## Première méthode
def lag_elm(i,x,t): # renvoie l'image de t par le i-ème polynome de Lagrange
n = len(x)
p1 = 1
p2 = 1
for k in [ j for j in range(n) if j!=i ]:
p1 = p1 * ( t - x[k] )
p2 = p2 * ( x[i] - x[k])
return p1/p2
def lag1(x,y): # renvoie le poly de Lagrange associé à (x,y)
n = len(x)
return lambda t : sum( y[i] * lag_elm(i,x,t) for i in range(n))
## Deuxième méthode
# Création d'une matrice de Vandermonde à partir d'un vecteur v
def vd(v):
v = np.reshape(v,(len(v),1))
A = np.ones((len(v),1))
for i in range(1,len(v)):
A = np.concatenate((A,v**i),1)
return A
def lag2(x,y): # renvoie le poly de Lagrange associé à (x,y)
V = vd(x)
p = np.linalg.solve(V,y)
return lambda t : sum( p[i]*t**i for i in range(len(x)))
######## Exercice 2 ########
f1 = lambda x : np.sin( np.pi * x )
t = np.linspace(-1,1,100) # subdivision pour l'intervalle [-1,1]
f1t = [f1(x) for x in t] # image des pts de la subdivision par f1
plt.figure()
plt.plot(t,f1t, label = 'courbe de f1 ')
for n in range(3,7):
X = np.arange(-1,1+2/n,2/n) # les noeuds x_i
Y = [f1(x) for x in X] # les images des noeuds par f1
L = lag1(X,Y)
Lt = [ L(x) for x in t ]
plt.plot(t, Lt, linestyle = ':' , label = ' courbe de L_'+str(n)+'(f1)')
plt.grid()
plt.legend(loc = 'best')
plt.show()
######## Exercice 3 ########
f2 = lambda x:1/(1+8*x**2)
f2t = [f2(x) for x in t]
# Question 1
plt.figure()
plt.plot(t,f2t, label = 'courbe de f2 ')
for n in [10,12,15,16]:
X = np.arange(-1,1+2/n,2/n)
Y = [f2(x) for x in X]
L = lag1(X,Y)
Lt = [ L(x) for x in t ]
plt.plot(t, Lt, linestyle = ':' , label = ' courbe de L_'+str(n)+'(f2)')
plt.grid()
plt.legend(loc = 'best')
plt.title( 'Interpolaton aux noeudx equidistants' )
plt.show()
# Question 2
plt.figure()
plt.plot(t,f2t, label = ' courbe de f1 ')
for n in [10,12,15,16]:
X = [ np.cos((2*k+1)*np.pi/(2*n+2)) for k in range(n+1)]
Y = [f2(x) for x in X]
L = lag1(X,Y)
Lt = [ L(x) for x in t ]
plt.plot(t, Lt, label = ' courbe L_'+str(n)+'(f1)')
plt.grid()
plt.legend(loc ='best')
plt.title('interpolation aux noeuds de Tchebychev')
plt.show()
######## Exercice 4 ########
"""
L'idée ici est d'utiliser une matrice triangulaire
Le tableau de l'exemple 3 du cours de M.Ziyat se représente ainsi
[
[0 , -1 , 1 , 3/8 , -77/120 , 167/960]
[2 , 1 , 5/2 , -17/6 , 3/4 , 0 ]
[4 , 6 , -6 , 5/3 , 0 , 0 ]
[5 , 0 , 2/3 , 0 , 0 , 0 ]
[8 , 2 , 0 , 0 , 0 , 0 ]
]
On remplie colonne par colonne
"""
def p_n(x,k,t):
p = 1
for i in range(k):
p = p*(t - x[i])
return p
def dif_div(x,y):
n = len(x)
D = np.zeros((n,n+1))
for i in range(n):
D[i,0] = x[i]
D[i,1] = y[i]
for j in range(2,n+1):
for i in range(n - (j-1)):
D[i,j] = ( D[i+1,j-1] - D[i,j-1] ) / ( D[i+j-1,0] - D[i,0] )
C = D[0,1:]
return lambda t : sum( C[k] * p_n(x,k,t) for k in range(n) )