Você está na página 1de 8

Interpolao

1. Interpolao polinomial

Seja f(x) uma funo, ento existe um polinmio p(x
i
), tal que

p(x
i
) = f(x
i
), para i 0, 1, 2, ..., n

Forma de Lagrange

=
= + + + =
n
0 k
n
k
k
n
n n
n
1
1
n
0
0
) x ( L ) x ( f ) x ( L ) x ( f ) x ( L ) x ( f ) x ( L ) x ( f ) x ( p

no qual ) x ( L
n
k
so os polinmios de Lagrange:

=
+
+

=


=
n
k i
0 i
i k
i
n k 1 k k 1 k k 1 k 0 k
n 1 k 1 k 1 0 n
k
) x x (
) x x (
) x x ( ) x x )( x x ( ) x x )( x x (
) x x ( ) x x )( x x ( ) x x )( x x (
) x ( L




Observe que 1 ) x ( L
k
n
k
= e 0 ) x ( L
i
n
k
= para i k.

Exemplo
Encontrar o polinmio que interpola a funo f(x) = 1/x
2
nos pontos x
0
= 2, x
1
= 2,5 e x
2
= 4.

Como sero usados trs pontos, o polinmio interpolador tem grau 2:

10 x 5 , 6 x
) 4 2 )( 5 , 2 2 (
) 4 x )( 5 , 2 x (
) x x )( x x (
) x x )( x x (
) x ( L
2
2 0 1 0
2 1 2
0
+ =


=


=

3 / ) 32 x 24 x 4 (
) 4 5 , 2 )( 2 5 , 2 (
) 4 x )( 2 x (
) x x )( x x (
) x x )( x x (
) x ( L
2
2 1 0 1
2 0 2
1
+ =


=


=

3 / ) 5 x 5 , 4 x (
) 5 , 2 4 )( 2 4 (
) 5 , 2 x )( 2 x (
) x x )( x x (
) x x )( x x (
) x ( L
2
1 2 0 2
1 0 2
2
+ =


=


=

Calculando os valores: f(x
0
) = 1/2
2
= 0,25, f(x
1
) = 1/2,5
2
= 0,16 e f(x
3
) =
2
= 0,0625 e
substituindo na equao (2), vem que

p
2
(x) = 0,25 (x
2
6,5x + 10) + 0,16/3 (-4x
2
+ 24x 32) + 0,0625/3 (x
2
4,5x + 5)

p
2
(x) =0,0575x
2
0,4388x + 0,8975

Prtica no Matlab

>> x = [2 2.5 4];
>> y = 1./x.^2;
>> xint = 2:0.1:4;
>> p = [0.0575 -0.4388 0.8975];
>> yint = polyval(p,xint);
>> plot(x,y,'o',xint,yint)


Roteiro para o clculo de valor interpolado pelo polinmio de Lagrange:

% LAGRANGE.M Interpolacao com polinomios de Lagrange de grau arbitrario
%
% Dados de entrada: x,y = dados tabulados
% xint = ponto no qual a funcao sera interpolada
%
% Saida: yint = valor de y em x = xint obtido por interpolacao com
% polinomio de grau n-1, onde length(y) = length(x) = n

dxi = xi - x; % vetor com os valores de xi - x(1), xi - x(2), ...
n = length(x); % grau do polinomio: n-1
L = zeros(size(y)); % pre-alocacao de L

% Funcoes base do polinomio de Lagrange, L(j)
L(1) = prod(dxi(2:n))/prod(x(1)-x(2:n)); % j = 1
L(n) = prod(dxi(1:n-1))/prod(x(n)-x(1:n-1)); % j = n
for j = 2:n-1
num = prod(dxi(1:j-1))*prod(dxi(j+1:n));
den = prod(x(j)-x(1:j-1))*prod(x(j)-x(j+1:n));
L(j) = num/den;
end
yint = sum(y.*L); % Calcula o polinomio: soma de y(j)*L(j), j=1..n


Forma de Newton

) x x ( ) x x )( x x ( c ) x x )( x x ( c ) x x ( c c ) x ( p
n 1 0 n 1 0 2 0 1 0
+ + + + =

) x x ( ) x x )( x x ( ) x ( A ) x ( p ) x ( f erro
n 1 0
= =

na qual:
)! 1 n (
) x ( f
) x ( A
) 1 n (
+
=
+
e c
0
= f(x
0
)

Definio de diferena dividida:

k
k 1 k 1 0 1 k 1 0
k 1 k 1 0
x x
) x , x , , x , x ( f ) x , x , , x , x ( f
) x , x , x , , x , x ( f




Para k = 0 e x = x
1
:
1
0 1
0 1
1 0
c
x x
) x ( f ) x ( f
) x , x ( f =

=

Para k = 1 e x = x
2
: ) x x ( c ) x , x ( f
x x
) x ( f ) x ( f
) x , x ( f
1 2 2 1 0
0 2
0 2
2 0
+ =

=
de modo que: ) x , x , x ( f
x x
) x , x ( f ) x , x ( f
c
2 1 0
1 2
1 0 2 0
2
=

=

) x , , x , x ( f c
k 1 0 k
= , k = 0, 1, 2, ..., n

Exemplo
Encontrar o polinmio na forma de Newton que interpola os dados abaixo a partir da tabela de
diferenas divididas.

x 1 2 4 5
y 0 2 12 20

Tabela de diferenas divididas:

x
i
f(x
i
) f = f(x
i
,x
i+1
)
2
f = f(x
i
,x
i+1
,x
i+2
)
3
f = f(x
i
,x
i+1
, x
i+2
, x
i+3
)
1
2
4
5
0
2
12
20
2
5
8
1
1
0

Os coeficientes do polinmio interpolador so:

0 ) x , x , x , x ( f c , 1 ) x , x , x ( f c
2 ) x , x ( f c , 0 ) x ( f c
3 2 1 0 3 2 1 0 2
1 0 1 0 0
= = = =
= = = =


O polinmio interpolador descrito por: p(x) = 2(x-1) + (x-1)(x-2) = x(x-1)


Funo para o clculo de valor interpolado pelo polinmio de Newton:

function yint = newtint(x,y,xint)
% NEWTINT.M Interpolacao com polinomios de Newton de grau arbitrario
%
% Sintaxe: yhat = newtint(x,y,xhat)
%
% Entrada: x,y = vetores contendo os valores tabulados de y = f(x)
% xint = vetor de x para o qual a funcao sera interpolada
%
% Saida: yint = vetor de y com os valores interpolados
%
% Note: Degree of interpolating polynomial is implicitly specified
% by the length of the x and y vectors. If n = length(y) then
% yhat is evaluated with a polynomial of degree (n-1)

n = length(y);
if length(x) ~= n,
error('x e y nao sao compativeis');
end

% --- Construct polynomial coefficients from diagonal of div.-diff. table
c = y(:); % First column is zeroth-order difference, f[x_i] = y_i
for j = 2:n
for I = n:-1:j % Work backward to keep from overwriting unused data
c(i) = (c(i)-c(i-1))/(x(i)-x(i-j+1));
end
end

% --- Nested evaluation of the polynomial
yhat = c(n);
for i = n-1:-1:1
yhat = yhat.*(xhat-x(i)) + c(i); % Array op allows vector of xhats
end

% --- optional output
if nargout>1
yn2 = c(n-1); % begin evaluation of polynomial of degree n-2
for i=n-2:-1:1
yn2 = yn2.*(xhat-x(i)) + c(i);
end
dy = yhat - yn2; % difference of interpolants of degree n-2 and degree
n-1
if nargout>2, cout = c; end % copy coefficients to output variable
end


Interpolao por splines

Geralmente, poderia se esperar que ao se usar um polinmio interpolador de maior
ordem, a qualidade da interpolao fosse aumentando. Infelizmente, isto nem sempre
verdadeiro e para algumas funes, o aumento da ordem do polinmio interpolador tende a
aumentar a tendncia oscilatria dos valores calculados pelo polinmio. Este um problema
conhecido por instabilidade numrica. A Fig. 1 mostra um famoso exemplo pelo qual Carl
Runge provou que para pontos extremos equidistantes o erro mximo se aproxima do infinito
medida que o grau do polinmio interpolador n .

-5 -4 -3 -2 -1 0 1 2 3 4 5
-0.5
0
0.5
1
1.5
2
x
y
f(x) = 1/(1 + x
2
)
Polinomio de grau 10


O polinmio interpolador por splines definido por:

) x ( C ) x ( C ) x ( C ) x ( s
k k 2 2 1 1
+ + + =

no qual C
i
so os coeficientes da combinao linear,
i
(x) so chamadas de funes base e k a
dimenso do espao vetorial.

Funes base para splines lineares (n = 1)

> <

=
+
+
+
+

1 i 1 i
1 i i
i 1 i
1 i
i 1 i
1 i i
1 i
i
x x ou x x se , 0
x x x se ,
x x
x x
x x x se ,
x x
x x
) x (

) x ( C ) x ( C ) x ( C ) x ( s
k k 2 2 1 1
+ + + =

Se a partio do intervalo for uniforme (x
i+1
x
i
= h), a funo base
i
(x) expressa
por meio da mudana de variveis na funo:



+
=
] 1 , 1 [ x se , 0
] 1 , 0 [ x se , x 1
] 0 , 1 [ x se , x 1
) x ( L

de onde vem que: |
.
|

\
|

= i
h
x x
L ) x (
0
i
, para i = 0, 1, 2, ..., n


Funes base para splines cbicos (n = 3)



Funo para o clculo de valores interpolados por polinmios spline:

function [yhat,aa,bb,cc,dd] = splint(x,y,xhat,opt1,opt2)
% splint Cubic-spline interpolation with various end conditions
%
% Synopsis: yhat = splint(x,y,xhat)
% yhat = splint(x,y,xhat,endType)
% yhat = splint(x,y,xhat,fp1,fpn)
% [yhat,a,b,c,d] = splint(x,y,xhat)
% [yhat,a,b,c,d] = splint(x,y,xhat,endType)
% [yhat,a,b,c,d] = splint(x,y,xhat,fp1,fpn)
%
% Input: x,y = vectors of discrete x and y = f(x) values
% xhat = (scalar or vector) x value(s) where interpolant is
evaluated
% endType = (string, optional) either 'natural' or 'notaKnot';
used
% to select either type of end conditions. End conditions must
be
% same on both ends. Default: endType='notaKnot'. For fixed
slope
% end conditions, values of f'(x) are specified, not endType
% fp1 = (optional) slope at x(1), i,e., fp1 = f'(x(1))
% fpn = (optional) slope at x(n), i,e., fpn = f'(x(n));
%
% Output: yhat = (vector or scalar) value(s) of the cubic spline
interpolant
% evaluated at xhat. size(yhat) = size(xhat)
% a,b,c,d = (optional) coefficients of cubic spline interpolants

% --- Process optional input arguments
if nargin<3
error('minimum of three input arguments needed');
elseif nargin==3
endType = 'notaknot';
elseif nargin==4 % four input arguments => natural or not-a-knot end
conditions
if ~ischar(opt1)
error('Third argument must be a string indicating type of end
conditions');
end
if strncmp('not',lower(opt1),3)
endType = 'notaknot';
elseif strncmp('nat',lower(opt1),3)
endType = 'natural';
else
error(sprintf('endType = %s not allowed',endType));
end
elseif nargin==5 % five input arguments => fixed slope end conditions
if ischar(opt1) | ischar(opt2)
error('Fourth, and fifth arguments must be numbers');
end
yp1 = opt1; ypn = opt2; endType = 'fixSlope';
else
error(sprintf('%d input arguments not allowed',nargin));
end

% --- Set up system of equations for b(i)
x = x(:); y = y(:); xhat = xhat(:); % convert to column vectors
n = length(x);
dx = diff(x); % Vector of x(i+1) - x(i) values
divdif = diff(y)./dx; % divided difference, f[x(i),x(i+1)]

alpha = [0; dx(1:n-2); 0]; % sub diagonal
bbeta = [1; 2*(dx(1:n-2)+dx(2:n-1)); 1]; % main diagonal
gamma = [0; dx(2:n-1); 0]; % super diagonal
A = tridiags(n,bbeta,alpha,gamma); % Sparse, tridiagonal matrix
delta = [ 0; 3*(divdif(2:n-1).*dx(1:n-2) + divdif(1:n-2).*dx(2:n-1)); 0 ];

% --- Modify system of equations as appropriate for the end conditions
if strncmp('not',lower(endType),3) % not a knot
A(1,1) = dx(2); A(1,2) = dx(1) + dx(2); % Equation for b(1)
delta(1) = ( dx(2)*(2*dx(2)+3*dx(1))*divdif(1)...
+ dx(1)*dx(1)*divdif(2) ) /(dx(1)+dx(2));
A(n,n-1) = dx(n-2) + dx(n-1); A(n,n) = dx(n-2); % Equation for b(n)
delta(n) = ( dx(n-2)*(2*dx(n-2)+3*dx(n-1))*divdif(n-1) ...
+ dx(n-1)*dx(n-1)*divdif(n-2) ) / (dx(n-2)+dx(n-1));
elseif strncmp('nat',lower(endType),3) % natural end conditions
A(1,2) = 0.5; delta(1) = 1.5*divdif(1); % y''(x(1)) = 0
A(n,n-1) = 1; A(n,n) = 2; delta(n) = 3*divdif(n-1); % y''(x(n)) = 0
elseif strncmp('fix',lower(endType),3) % prescribed slope end
conditions
delta(1) = yp1; delta(n) = ypn;
else
error(sprintf('Logic error: endType = %s',endType));
end

% --- Solve the system for b
mmdflag = spparms('autommd'); % Store minimum degree ordering flag
spparms('autommd',0); % Set that flag to zero
b = A\delta; % Solve the system
spparms('autommd',mmdflag); % Reset the minimum degree ordering flag

% --- Compute coefficients of spline interpolants
a = y(1:n-1);
c = (3*divdif - 2*b(1:n-1) - b(2:n))./dx;
d = (b(1:n-1) - 2*divdif + b(2:n))./dx.^2;
b(n) = []; % discard b(n)

% --- Locate each xhat value in the x vector
i = zeros(size(xhat)); % i is index into x such that x(i) <= xhat <=
x(i+1)
for m=1:length(xhat) % For vector xhat: x( i(m) ) <= xhat(m) <= x(
i(m)+1 )
i(m) = binSearch(x,xhat(m));
end

% --- Nested, vectorized evaluation of the piecewise polynomials
xx = xhat - x(i);
yhat = a(i) + xx.*(b(i) + xx.*(c(i) + xx.*d(i)) );

if nargout>1, aa = a; bb = b; cc = c; dd = d; end % optional outputs



Funo de interpolao no Matlab

INTERP1: Interpolao 1-D (tabela).

Sintaxe: YI = INTERP1(X,Y,XI)
A funo INTERP1 fornece os valores interpolados em YI dos valores da funo Y nos pontos
do vetor XI. O vetor X especifica os pontos nos quais os valores de Y so fornecidos.

YI = INTERP1(X,Y,XI,'method') especifica mtodos alternativos de interpolao. O
mtodo default a interpolao linear. Os mtodos disponveis so:
'nearest' - interpolao pelos vizinhos mais prximos
'linear' - interpolao linear
'spline' - interpolao spline cbica (SPLINE)
'pchip' - interpolao por polinmio de Hermite cbico (piecewise cubic Hermite
interpolation - PCHIP)
'cubic' - o mesmo que 'pchip'


Exemplo:

>> x = 0:10; y = sin(x); xi = 0:.25:10;
>> yi = interp1(x,y,xi); plot(x,y,'o',xi,yi)


Alternativamente para o polinmio spline pode ser usada a funo SPLINE:
SPLINE: Interpolao por spline cbica.
Sintaxe: YY = SPLINE(X,Y,XX)
A funo SPLINE utiliza a interpolao por spline cbica para calcular os valores interpolados
YY da funo Y nos pontos contidos no vetor XX. O vetor X especifica os pontos nos quais os
valores de Y so dados.

Exemplo
Neste exemplo, gerada a funo seno e ela amostrada para uma malha mais fina atravs de
spline:

>> x = 0:10; y = sin(x);
>> xx = 0:.25:10;
>> yy = spline(x,y,xx);
>> plot(x,y,'o',xx,yy)

Exemplo
Neste exemplo usada uma interpolao por spline completa na qual as inclinaes das
extremidades so pr-determinadas. So utilizadas inclinaes zero nas extremidades da
funo interpolante para os valores de uma dada distribuio:

>> x = -4:4; y = [0 .15 1.12 2.36 2.36 1.46 .49 .06 0];
>> cs = spline(x,[0 y 0]);
>> xx = linspace(-4,4,101);
>> plot(x,y,'o',xx,ppval(cs,xx),'-');


Exerccio

1. Encontrar os polinmios interpoladores de Lagrange para as seguintes funes:
(a) sen x, para os valores de x = [0, 1.2, 3, 4.2, 5]
(b) e
x
, para os valores de x = [0, 0.5, 2, 3]
(c) ln x, para os valores de x = [1, 1.5, 2, 3.8, 4]

Você também pode gostar