Sei sulla pagina 1di 13

Logintoeditacopy.

Download.

Otherpublisheddocuments...

Interpolacion
652daysagobykeltran

Interpolacinpolinmica
Enmuchasocasionesconocemoselvalordeunafuncinf(x) enunconjuntodepuntosx 0 , x 1 , , x N1 ,peronocontamosconninguna
expresinanalticadef(x) quenospermitacalcularlaencualquierpuntoarbitario.Porejemplo,losvaloresf(x i )puedenprovenirdemedidas
fsicasodealgnclculonumricolargoquenopuedeexpresarseenunaformafuncionalsencilla.Amenudo,lospuntosx i estn
equiespaciados,peronoesnecesario.
Elproblemaquenosplantearemossereldeestimarf(x) parax arbitariomedianteunacurva"suave"quepaseporlospuntos(x i , f(x i )).Si
elvalordex estentreelmenoryelmayordelosx i ,entoncestendremosunproblemadeinterpolacin,mientrasque,encasocontrario,se
tratardeunproblemadeextrapolacin.
Losesquemasdeinterpolacinyextrapolacindebenmodelarlafuncin,entreomsalldelospuntosconocidos,mediantealgunaforma
funcionalrazonable.Estaformadeberaserlosuficientementegeneralcomoparapoderaproximarunaclaseampliadefuncionesquepodran
surgirenlaprctica.Entrelasmscomunesquesesuelenemplear,encontramosalospolinomios.Apartedelospolinomios,tambinseutilizan
confrecuenciafuncionesracionalesytrigonomtricas(senosycosenos).Aqu,noscentraremosenelproblemadeinterpolacinusando
polinomios,quesueleconocersecomoelproblemadeinterpolacinpolinmica.
Conceptualmente,elprocesodeinterpolacintienedosfases:(1)encontrar(unanicavez)lafuncinquese"ajusta"alosdatos
suministrados,y(2)evaluar(tantasvecescomosedesee)dichafuncinenunvalorx .Sinembargo,esteprocedimientoendosfasesnoesel
mejoraseguirenlaprctica.Normalmente,desdeelpuntodevistacomputacional,esmenoseficienteymssusceptibleaerroresderedondeo
comparadoconotrosmtodosqueconstruyenlaestimacindef(x) apartirdelosNvalorestabuladoscadavezqueseanecesario.Muchos
esquemasprcticoscomienzanenunpuntocercanof(x i )yvanaadiendounasucesindecorreccionesdecrecientesamedidaqueseva
incorporandolainformacindeotrosf(x i )scercanos.Sitodosecomportacorrectamente,laltimacorreccinserlamenorypodrusarse
comounacota(norigurosa)delerrorenlaestimacin.Enestetipodeesquemas,podemoshablartambindedosfases,peroahoraseran:(1)
encontrarlaposicininicialadecuadaenlatabla( x i oi ),y(2)realizarlainterpolacinutilizandoMvalorescercanos(porejemplo,"centrados"
enx i ).
ElnmerodepuntosMutilizadoenlainterpolacin,menos1 ,sedenominaordendelainterpolacin.Aumentarelordennoaumenta
necesariamentelaprecisindelaestimacin,sobretodoenelcasodelainterpolacinpolinmica.Silospuntosadicionalesdistanmuchodeall
dondequeremosestimarlafuncin,elpolinomioresultantedemayorgrado,consusrestriccionesadicionales,tiendeaoscilarampliamente
entrelosvalorestabulados.Estaoscilacinpuedenotenernadaqueverconelcomportamiente"real"delafuncin.Noobstante,esrazonable
pensarquesilospuntosadicionalesestncercadedondequeremosestimarlafuncin,entoncesestosayudarnamejorarlaaproximacin,
peroengeneralsercomplicadoaadirestetipodepuntos.
Enelcasodelainterpolacinpolinmica,elpeorcasoparaladisposicindelosx i sesqueseencuentrenequiespaciados.Desgraciadamente,
estesueleserelcasomscomn.Lainterpolacinpolinmicaconpolinomiosdegradoaltoenpuntosequiespaciadosesunproblemamal
condicionado,esdecir,pequeasvariacionesenlosdatospuedenresultarengrandesdiferenciasenlasoscilacionesentrelospuntos.As,si
fueramosaumentandoelordendelainterpolacin,estpicoqueloserroresdecrezcanalprincipio,perohastaciertopunto,apartirdelcuallos
erroresempezaranaexplotar.Esporelloquehayqueserprecabidoconlasinterpolacionesderdenesaltos.Lorazonableesusarentre3y4
puntos,yentre5y6comomximo,anoserquesetengauncontrolrigurososobrelaestimacindeloerrores.Deestaforma,lorecomendado
esmantenerfijoelordendelainterpolacinaM(usandoM 1puntos),sinimportarelnmerototaldepuntosNdequedispongamos.
Podramosdecirqueestaformadeinterpolareslocal,yaquenoutilizatodoslospuntosdisponibles.
Enalgunasocasiones,esnecesariomantenerlacontinuidaddelasfuncionesinterpolantesydesusderivadas.Enestoscasos,usaremosloque
seconocecomointerpolacinporsplines.Aqulaideaesaproximarlafuncinf(x) porunpolinomiocbicoencadaintervalo[x i , x i+1 ] ,de
formaquelafuncinaproximadaseaunafuncinatrozosformadapordichospolinomios,continuayconlasegundaderivadacontinuaentodos
losx i s(salvo,quiz,enlosextremos).Enconcreto,aestetipodeinterpolacinseledenominainterpolacinporsplinescbicos.

Elproblemadelainterpolacinpolinmica.MatrizdeVandermonde
Engeneral,podemosplantearelproblemadelainterpolacinpolinmicadeordenMcomoelproblemadeencontrarunpolinomiodegrado
M 1quepaseporlosM puntosy 0 = f(x 0 ) ,y 1 = f(x 1 ), , y M1 = f(x M1 ) .Silospuntosx i ssondistintos,esfcildemostrarquesolo
hayunpolinomioconesascaractersticas.Siexpresamosdichopolinomiocomo:
P M (x) = a 0 + a 1 x + + a M1 x

M1

lacondicindeinterpolacinvendrarepresentadaporlaecuaciones:
P M (x i ) = y i (i = 0, , M 1),

queformaunsistemalinealdeMecuacionesconincgnitasloscoeficientesdelpolinomioa 0 , , a M1 .Siloescribimosenformamatricial,
tenemos:
1

x0

x1

x M1

M2
0
M2
1

x
x

M2
M1

M1
0
M1
1

M1
M1

a0

a1

a M1

y1

y M1

AlamatrizdecoeficientesseledenominamatrizdeVandermondeysepuededemostrarqueesnosingular,porloqueelsistemasera
compatibledeterminado,demostrandoaslaexistenciayunicidaddelpolinomiointerpolador.
Noobstante,resolverdichosistemanoeslamejormaneradehallarP M (x) ,alnoserlamseficienteypresentarproblemasdeestabilidad.

defPoliVandermonde(x,X,Y):
#MatrizdeVandermonde
V=matrix(RR,len(X),len(X),lambdai,j:X[i].n()^j)
#Resolversistema
P=V.solve_right(vector(Y))*vector([x^iforiinrange(0,len(X))])
returnP

Acontinuacin,veremosotrasformasmsadecuadasdeabordarelmismoproblema.

PolinomiointerpoladordeLagrange
UnaalternativapropuestaporLagrangeesescribirelpolinomiointerpoladorcomo:
P M (x) = a 0 0 (x) + + a M1 M1 (x),

donde
i (x) =

(x x 0 )(x x 1 ) (x x i1 )(x x i+1 ) (x x M1 )


(x i x 0 )(x i x 1 ) (x i x i1 )(x i x i+1 ) (x i x M1 )

sonlospolinomiosinterpoladoresdeLagrange,quesatisfacen
i (x j ) = {

i = j,

i j.

Esfcilcomprobarque,enestecaso,lacondicindeinterpolacinsesatisfacepara
ai = yi ,

(i = 0, , M 1).

Aunquedeestaformahayamosconseguidoreducirlacondicindeinterpolacinaunsistematrivial,debemosdarnoscuentadeque,en
general,lospolinomiosdeLagrangesonmsdifcilesdeevaluarquelosdeNewton(quevermeosmsadelante),que,asuvez,sonms
complicadosdeevaluarquelaspotenciasdex .

defPoliLagrange(x,X,Y):
P=sum(Y[i].n()*prod((xX[j].n())/(X[i].n()X[j].n())forjinrange(0,len(X))ifi<>j)foriin
range(0,len(X)))
returnexpand(P)

ErrordelpolinomiodeInterpolacindeLagrange
Supongamosqueinterpolamosuanfuncinfenn + 1 puntosusandounpolinomioPdegradon.Nosplanteamoscaleslamximadiferencia
quepodemosobtenerentreelverdaderovalordef(x) yelobtenidomediantesuaproximacinporP(x) .Encontradeloquepodiamosesperar
utilizarunmayorgradoenelpolinomiodeinterpolacinnodamayoraproximacinenvaloresdelafuncincomoveremosmsadelante(efecto
deRunge).Ahorabien,podemosobtenerunacotadelerrorteniendoencuentaelsiguiente:

Teorema.Seaf C

[a, b]yconsideremosx 0 , x 1 , , x n nodosenelintervalo[a, b] .SeaP(x) elplinomiodegradonqueinetrpolala


funcinfenlosnodosx 0 , x 1 , , x n ,entoncesdadocualquierx [a, b]setieneque:
(n+1)

1
x = f(x) P(x) =

paraalgnpunto x

(n+1)

(n + 1)!

) (x x j )
j=0

[a, b] .

Siconsideramoslanormadelinfinitoydefinimos

M = f

podemosobtenerunacotadelerrorparax

(n+1)

(x)

= m

f (n+1) (x)

x[a,b]

[a, b]como
n

M
x =

(n + 1)!

x x j

j=0

.
Yparaelintervalo[a, b] unacotamximade:
M
x[a,b] =

m
(n + 1)!

x[a,b]

deferrLagrange(f,x,X):
'''
Suponiendoqueconocemoslafuncinquequeremosinterpolar

( x x j )
j=0

f>funcin
x>valor
X>nodos
'''
#calculavalormaximoaproximadoquealcanzalafuncinenelintervalo
M=plot(abs(diff(f,len(X))),X[0],X[len(X)1]).ymax()
error=prod(abs(xX[j].n())forjinrange(0,len(X)))
iferror.is_real()==False:
#sibuscamosunacotadelerrorparaelintervalo
#calculavalormaximoaproximadoquealcanzalafuncinenelintervalo
error=plot(error,X[0],X[len(X)1]).ymax()
error=error*M/factorial(len(X))
returnerror

Ejemplo:acotacindelerrordelpolinomiodeinterpolacin
1. Considerandolafuncinf(x) = e x ,calcularelpolinomiodeinterpolacindegrado3ennodosequiespaciadosdelintervalo[0, 0.2] y
obtenerunacotadelerrorendichointervalo,ascomounacotadelerrorparax = 0.13ascomoelerrorabsoluto|f(0.3) P 3 (0.3)| .

2. Considerandolafuncinf(x) = sin(x) ,calcularelpolinomiodeinterpolacindegrado1ennodosequiespaciadosdelintervalo[0, 2 ] y

obtenerunacotadelerrorendichointervalo,ascomounacotadelerrorparax = 3 ascomoelerrorabsoluto|f( 3 ) P 1 ( 3 )| .

f(x)=e^x
orden=3
X=[0+i*(.2)/(orden)foriinrange(orden+1)]
Y=[f(X[i])foriinrange(len(X))]
P(x)=PoliLagrange(x,X,Y)
punto=0.13
print"*cotaerrorenintervalo["+X[0].str()+","+X[len(X)1].str()+"]:",errLagrange(f,x,X)
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
show(plot(f,X[0],X[len(X)1],color='orange')+point((punto,f(punto)),size=30)+point(zip(X,Y),color='red')+plot(P,
(X[0],X[len(X)1]),color='green'),figsize=3)
*cotaerrorenintervalo[0.000000000000000,0.200000000000000]:
1.00492099002e06
*cotaerrorenx=0.130000000000000:9.77687670768024e8
*errorabsolutoenx=0.130000000000000:8.90312068513310e8

f(x)=sin(x)
orden=1
X=[0+i*(pi.n()/2)/(orden)foriinrange(orden+1)]
Y=[f(X[i])foriinrange(len(X))]
P(x)=PoliLagrange(x,X,Y)
print"*cotaerrorenintervalo["+X[0].str()+","+X[len(X)1].str()+"]:",errLagrange(f,x,X)
punto=pi.n()/3
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
show(plot(f,X[0],X[len(X)1],color='orange')+point((punto,f(punto)),size=30)+point(zip(X,Y),color='red')+plot(P,
(X[0],X[len(X)1]),color='green'),figsize=3)
*cotaerrorenintervalo[0.000000000000000,1.57079632679490]:
0.308421505572
*cotaerrorenx=1.04719755119660:0.274155677808038
*errorabsolutoenx=1.04719755119660:0.199358737117772

PolinomiointerpoladordeNewton.Diferenciasdivididas
OtraalternativaesreescribirelpolinomioP M (x) entrminosdeotrospolinomiosdegradoM 1deformaquelacondicindeinterpolacin
quedeexpresadadeformamsnatural.As,Newtonpropuso:
P M (x) = a 0 n 0 (x) + a 1 n 1 (x) + + a M1 n M1 (x),

donde
n i (x) = (x x 0 )(x x 1 ) (x x i1 )

seconocencomolospolimoniosinterpoladoresdeNewton,quetienenlaimportantepropiedad:
n i (x j ) = 0,

j < i

graciasalacual,elsistemadeecuacionesparahallarelpolinomiointerpoladorseratriangulary,portanto,muchomssencilloderesolver.
Ntesetambinquea 0 n 0 (x) + a 1 n 1 (x) + + a l n l (x) eselpolinomiodegradol quepasaporlospuntos(x 0 , f(x 0 )),
(x 1 , f(x 1 )), , (x l1 , f(x l1 )) .
Parahallarloscoeficientesa i ,Newtondiseoelmtododelasdiferenciasdivididas,enelqueloscoeficientesdeP M (x) seescriben
recursivamentecomo:
a i = [y 0 , , y i ] (i = 0, , M 1),

donde
[y k ] = y k ,

(k = 0, , M 1)

[y k+1 , , y k+j ] [y k , , y k+j1 ]


[y

,,y

k+j

] =

(k = 0, , M 1 j), (j = 1, , M 1).

x k+j x k

UnalgoritmoeficienteparalaevaluacindelpolinomiointerpoladorP M (x) eselalgoritmodeNevillebasadoenlarecurrenciadelasdiferencias


divididasdeNewton.

defPoliNewton(x,X,Y):
Q=matrix(SR,len(X),len(X))
foriinrange(0,len(X)):
Q[i,0]=Y[i].n()
foriinrange(1,len(X)):
forjinrange(1,i+1):
#calculalasdiferenciasdivididas
Q[i,j]=(Q[i,j1].n()Q[i1,j1].n())/(X[i].n()X[ij].n())
#calculaelpolinomio,siendoloscoeficientesloselementosdeladiagonalprinicpal
P=sum(expand(Q[i,i].n()*prod((xX[j].n())forjinrange(0,i))foriinrange(0,len(X))))
returnexpand(P)

AlgoritmodeNeville
Estealgoritmosebasaenelsiguienteesquema:DenotamosporP 0 alvalorenx delnicopolinomiodegradoceroquepasapor(x 0 , y 0 ),es
decir,P 0 = y 0 .Anlogamente,definimosP 1 ,P 2 , , P M1 .Acontinuacin,denotamosporP 01 alvalorenx delnicopolinomiodegrado1
quepasapor(x 0 , y 0 )y(x 1 , y 1 ),yanlogamenteP 12 ,P 23 , , P (M2)(M1) .YasseguimosconpolinomiosdemayorgradohastaP 01(M1) ,
queeselvalorenx delnicopolinomiodegradoM 1quepasaportodoslosMpuntos,estoes,P 01(M1) = P M (x).TodoslosPspueden
disponerseenunatablaconancestrosalaizquierdaquellevanaunnicodescendienteenelextremoderecho.Porejemplo,paraM = 4,
x0 :

y0 = P0

x1 :

y1 = P1

P 01
P 012
P 12
x2 :

x3 :

y3 = P3

= P2

P 0123 .
P 123

P 23

ElalgoritmodeNevilleesunaformarecursivadellenarlosnmerosdelatabla,unacolumnacadavez,deizquierdaaderecha.Estbasadoen
larelacinderecurrencia(derivadadeladelasdiferenciasdivididas):
(x x i+m )P i(i+1)(i+m1) + (x i x)P (i+1)(i+2)(i+m)
P i(i+1)(i+m) =

.
x i x i+m

defNeville(x,X,Y):
Q=matrix(SR,len(X),len(X))
foriinrange(0,len(X)):
Q[i,0]=Y[i]
foriinrange(1,len(X)):
forjinrange(1,i+1):
#matrizquecontienetodoslospolinomiosdeinterpolacionobtenidosporrecurrencia
Q[i,j]=expand(((xX[ij])*Q[i,j1](xX[i])*Q[i1,j1])/(X[i]X[ij]))

P=Q[len(X)1,len(X)1]
returnexpand(P)

#funcinquenospermiteagrupartodoslosmtodos
definterpola(x,X,Y,tip='Nev'):
iftip=='Nev':
returnNeville(x,X,Y)
eliftip=='Van':
returnPoliVandermonde(x,X,Y)
eliftip=='Lag':
returnPoliLagrange(x,X,Y)
eliftip=='New':
returnPoliNewton(x,X,Y)
else:
print"mtododesconocido"

Ejemplosdeaplicacindelasdistintasimplementacionesdel
PolinomiodeInterpolacin+ComandosdeSAGE
X=[0.7847,1.0320,2.3414,3.6836,4.9530]
Y=[2.3610,2.4706,6.8767,11.7008,15.6005]
fortipoin["Van","Lag","New","Nev"]:
Q(x)=interpola(x,X,Y,tipo)
printtipo+">",Q(x)
show(plot(Q,0,5,color="red")+point(zip(X,Y),color="green"),xmin=0,xmax=5,figsize=2)

#ComandoparapolinomiodeinterpolacinpropiodeSAGE
PR=PolynomialRing(RR,"x")
Q=PR.lagrange_polynomial(zip(X,Y),algorithm="divided_difference")
print"SAGEdiferenciasdivididas>",Q
pares=((X[i],Y[i])foriinrange(len(X)))
show(plot(Q,0,5,color="red")+point(zip(X,Y),color="green"),xmin=0,xmax=5,figsize=2)
Q=PR.lagrange_polynomial(zip(X,Y),algorithm="neville")[1]
print"SAGEneville>",Q
pares=((X[i],Y[i])foriinrange(len(X)))
show(plot(Q,0,5,color="red")+point(zip(X,Y),color="green"),xmin=0,xmax=5,figsize=2)

Ejemplo
Supongamoslosdatosdadosenlasiguientetabla:
X

25

caleselgradodelpolinomiodeinterpolacin?

X=[2,1,0,1,2,3]
Y=[5,1,1,1,7,25]
fortipoin["Van","Lag","New","Nev"]:
Q(x)=interpola(x,X,Y,tipo)
printtipo+">",Q(x)
show(plot(Q,X[0],X[len(X)1],color="red")+point(zip(X,Y),color="green"),figsize=3)

EFECTODE"Runge"
ElfenmenodeRungeesunproblema,debidoalafaltadeconvergenciapuntualdelospolinomiosinterpoladoresconrespectoalafuncin
consideradaalaumentarelnmerodenodos,quepuededarsecuandolosnodosestnigualmenteespaciados.Aumentemosprogresivamenteel
ordenparaobservarelfenmenoyademspodemosobservarlaefeicienciayaproximacindelclculodependiendodelmtodoescogido,
siendoeldeNevilleelmseficientedelosconsiderados.probarconorden10,15,25y40.

#funciondeRUNGE
f(x)=1/(1+25*x^2)
orden=10
X=[1+i*2/(orden)foriinrange(orden+1)]
Y=[f(X[i]).n()foriinrange(orden+1)]
fortipoin["Van","Lag","New","Nev"]:

P(x)=interpola(x,X,Y,tipo)
printP
printP(0.7)
show(plot(f,X[0],X[len(X)1],color='orange')+point(zip(X,Y),color='red')+plot(P,
(X[0],X[len(X)1]),color='green',ymax=1.2,ymin=.5),figsize=3)

Ejercicio
x

cos(x

Considerandolafuncinf(x) =
) ,calcularelpolinomiodeinterpolacindegrado15ennodosequiespaciadosdelintervalo[2, 2] y
2
obtenerunacotadelerrorendichointervalo,ascomounacotadelerrorparalospuntosx = 1yx = 2.5ascomoloserroresabsolutos
|f(1) P 15 (1)| y|f(2.5) P 15 (2.5)| .

f(x)=x^2*cos(x^2)/2
orden=15
X=[2+i*4/(orden)foriinrange(orden+1)]
Y=[f(X[i]).n()foriinrange(len(X))]
P(x)=interpola(x,X,Y,"Nev")
printP(x)
print"*cotaerrorenintervalo["+X[0].str()+","+X[len(X)1].str()+"]:",errLagrange(f,x,X)
punto=1
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
graf=point((punto,f(punto)),size=30)
punto=2.5
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
show(plot(f,2,2.5,color='orange')+point(zip(X,Y),color='red')+graf+point((punto,f(punto)),size=30)+plot(P,
(2,2.5),color='green'),ymin=2,figsize=5)

Ejercicio
Considerandolafuncinf(x) = sin(x) + log(x),calcularelpolinomiodeinterpolacindegrado6ennodosequiespaciadosdelintervalo[1, 5] y
obtenerunacotadelerrorendichointervalo,ascomounacotadelerrorparalospuntosx = 5yx = 7ascomoloserroresabsolutos
|f(5) P 6 (5)| y|f(7) P 6 (7)| .

f(x)=sin(x)+log(x)
orden=6
X=[1+i*5/(orden)foriinrange(orden+1)]
Y=[f(X[i]).n()foriinrange(len(X))]
P(x)=interpola(x,X,Y,"Nev")
printP(x)
print"*cotaerrorenintervalo["+X[0].str()+","+X[len(X)1].str()+"]:",errLagrange(f,x,X)
punto=5
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
graf=point((punto,f(punto)),size=30)
punto=7
print"*cotaerrorenx="+punto.str()+":",errLagrange(f,punto,X)
print"*errorabsolutoenx="+punto.str()+":",abs(f(punto)P(punto)).n()
show(plot(f,0,7,color='orange')+point(zip(X,Y),color='red')+graf+point((punto,f(punto)),size=30)+plot(P,
(0,7),color='green'),figsize=5,xmax=7)

InterpolacinporSplinescbicos
Cuandoelnmerodedatosesgrande,lautilizacindeunainterpolacinploinmicanoresultaeficiente,yaquesibien,enlosnodostomalos
valores,epuedenproducirgardespicos(efectoRunge).Unaalternativaconsisteendetreminarunafuncinpolinomialesdefinidasatrozosque
sedenominansplines.Diremosquelafuncins(x)esunsplineenenelintervalo[a, b] ,siexisteunaparticindelintervalo
P = {a = x 0 < x 1 < x n = b}

detalformaques(x)esunploinomioen[x i , x i+1 ] ,i

= 0, 1, , n 1.lospuntosx i sedenominannodos.

Paraobtenercurvassuavesseutilizansplinescbicosdeclase2,esdecir,polinomiosdegrado3.Sillamamoss i (x) alarestriccindelspline


s(x)alintervalo[x i , x i+1 ], i = 0, 1, , n 1 ,enotnces
s i (x) = d i (x x i )

+ c i (x x i )

+ b i (x x i ) + a i i = 0, 1, , n 1,

porloquetendremos4incgnitasquedeterminarporcadaintervalo,ysitenemosnintervalos,tendremosquedeterminaruntotalde4n
coeficientes.Paraobtenerlospodemosconsiderarlascondicionesquetienenquecumplircadaspline:

n + 1

i. Condicionesdeinterpolacin( n + 1 ecuaciones):
s i (x i ) = f(x i ), i = 0, 1, , n 1, s n1 (x n ) = f(x n ).

ii. Condicionesdecontinuidadenlosnodosinteriores( n 1 ecuaciones):


s i (x i+1 ) = s i+1 (x i+1 ), i = 0, 1, , n 2.

iii. Condicionesdesuavidadennodosinteriores,primeraysegundaderivada( 2n 2 ecuaciones):

s (x i+1 ) = s
i

i+1

(x i+1 ) = s

(x i+1 ), i = 0, 1, , n 2
.

i+1

(x i+1 ), i = 0, 1, , n 2

Observemosqueobtenemosuntotalde4n 2 ecuaciones,portanto,necesitamosincluirdosnuevascondicionesparapoderdeterminarel
splines(x).Estascondicionesseimponenenlosextremosdelintervalo[a, b] ,siendolasmshabituales:
1. splinecbiconaturalconderivadassegundasnulasenlosextremos,esdecir
s

(a) = 0, s

n1

(b) = 0.

2. splinecbicosujetoimponiendocondicionesdependientes(derivadaprimera,f
s

(a) = f (a), s

(a) yf (b) )enloslmites,esdecir

n1

(b) = f (b).

Implementacin:
Llamemosh i = x i1 x i .
2
3
Teniendoencuentaques i (x i ) = f(x i ) = y i tenemosquea i = y i ey i+1 = a i + b i h i + c i h i + d i h i
Efectuandoalgunasmanipulacionesalgebricasyconlascondicionesdecontinuidadysuavidad,yhaciendos i (x i )
ci =

ri
2

;d i =

r i+1 r i

yb i =

6h i

Finlmente,teniendoencuentaque,porunlado,s i (x i )
parai = 1, 2, , n 2,n 2 ecuacionesdelaforma:

y i+1 y i

hi

hi

= b i ,yporotro,s (x i ) = s

i1

h i1 r i1 + 2(h i + h i1 )r i + h i r i+1 = 6[

= r i ,tenemosque:

(2r i + r i+1 )

(x i ) = b i1 + 2c i1 h i1 + 3d i1 h

(y i+1 y i )

hi

y i1

2
i1

obtenemos

h i1

considerandolacondicindesplinecbiconatural,conderivadassegundasnulasenlosextremos,obtenemoselsistema:
0

(y

h 0

2(h 0 + h 1 )

h1

h1

2(h 1 + h 2 )

h2

h n3

2(h n3 + h n2 )

h n2

r0

considerandolacondicindesplinecbicosujeto,cons 0 (a)

= f (a), ys

n1

y1 y0

2
1

6[

h1
h0

(y 3 y 2 )
y2 y1

6[

h
h
2
1
=

(
y

y
)
y

n1
n2
n2
n3

]
6[

h n2
h n3

r 1

r n2
r
n1

(b) = f (b),obtenemoselsistema:

(y 1 y 0 )

6[
f (a)]

h0

(y 2 y 1 )
y1 y0

6[

h1
h0

(
y

y
)
y

3
2
2
1

6[

h2
h1

y
y
(y n1 y n2 )

n2
n3
6[

h n2
h n3

y
y

2h 0

h
0

h0

2(h 0 + h 1 )

h1

h1

2(h 1 + h 2 )

h2

h n3

2(h n3 + h n2 )

h n2

h n2

2h n2

r0

r1

r
2

r n2

r n1

Resolviendoelsistema,tridiagonal,podemosobtenerlosr i coni =
Pudiendodefinir,as,unafuncinatrozosenlosintervalosdados.

defspline_natural(x,X,Y,trazador=False):
m=0

6[f (b)

n1

h n2

n2

0, 1, , n 1yfinlmenteloscoeficientesdecadaunodelossplines.

N=len(X)#numerodedatos
#a,b,c,anddcoeficientesdelossplinescubicos
a=mrange_iter([range(N)],sum)
b=mrange_iter([range(N)],sum)
c=mrange_iter([range(N)],sum)
d=mrange_iter([range(N)],sum)

#valoresauxiliaresparaelcculodea,b,cyd
alpha=mrange_iter([range(N)],sum)
h=mrange_iter([range(N)],sum)
l=mrange_iter([range(N)],sum)
mu=mrange_iter([range(N)],sum)
z=mrange_iter([range(N)],sum)

#trazadordelspline
S=mrange_iter([range(N)],sum)
#losa'ssonlosvaloresdelasimagenesdelvectorainterpolar
a=Y
#valoresiniciales
h[0]=X[1]X[0]
l[0]=1
mu[0]=0
z[0]=0
#valoresusadosenelcalculodelosc's(derivadassegundasr's/2)ReducimosporGauss
forninrange(1,N1):
h[n]=X[n+1]X[n]
alpha[n]=3/h[n]*(a[n+1]a[n])3/h[n1]*(a[n]a[n1])
l[n]=2*(X[n+1]X[n1])h[n1]*mu[n1]
mu[n]=h[n]/l[n]
z[n]=(alpha[n]h[n1]*z[n1])/l[n]
n=N1
c[n]=0
l[n]=1
z[n]=0
n=n1
#calculamoslosvaloresparac,b,ydMetododelasubidayformamoselpolinomiocubico
whilen>=0:
c[n]=(z[n]mu[n]*c[n+1])
b[n]=((a[n+1]a[n])/h[n]h[n]*(c[n+1]+2*c[n])/3)
d[n]=((c[n+1]c[n])/(3*h[n]))
S[n]=a[n]+b[n]*(xX[n])+c[n]*(xX[n])^2+d[n]*(xX[n])^3
n=n1
iftrazador:
#devuelvefuncionatrozosconcadaunodelosspline'scubicos
returnpiecewise([[(X[i],X[i+1]),expand(S[i])]foriinrange(N1)])
foriinrange(N1):
#devuelveelvalordelafuncinenelintervalocorrespondienteax
ifX[i]<=x<=X[i+1]:
P=S[i]
returnP
returnNone

PERFILALAR


Considerandolospuntosdadosenelfichero"naca2418.dat"referidosalperfilNACA2418,obtenerelsplinequemejoraproximaalospuntos
dados,teniendoencuentaqueencadanodohaydosimgenes,porlotantosedebenutilizardossplines,unoparalasimgenessuperioresy
otroparalasinferiores.

%hide
%auto
#PERFILALARENPARAMETRICAS
naca2418=open(DATA+'naca2418.dat')
naca2418.readline()
fromnumpyimportloadtxt
datosNACA2418=loadtxt(naca2418)
datosNACA2418=list(datosNACA2418)
par=[];Y=[];X=[]
foriinrange(len(datosNACA2418)):
par.append((datosNACA2418[i][0],datosNACA2418[i][1]))
show(points(par,color="red",size=50),xmin=0,xmax=1,ymax=.4,ymin=.4,figsize=4)

naca2418=open(DATA+'naca2418.dat')
naca2418.readline()
fromnumpyimportloadtxt
datosNACA2418=loadtxt(naca2418)
datosNACA2418=list(datosNACA2418)
paresNACA2418=[]
parsup=[];parinf=[];ysup=[];yinf=[];xsup=[];xinf=[]
foriinrange(len(datosNACA2418)):
ifdatosNACA2418[i][1]>=0:
parsup.append((datosNACA2418[i][0],datosNACA2418[i][1]))
ifdatosNACA2418[i][1]<=0:
parinf.append((datosNACA2418[i][0],datosNACA2418[i][1]))
parinf.sort();parsup.sort()
foriinrange(len(parinf)):
xinf.append(parinf[i][0]*1.)
yinf.append(parinf[i][1]*1.)
foriinrange(len(parsup)):
xsup.append(parsup[i][0]*1.)
ysup.append(parsup[i][1]*1.)

#muestraeltrazadorcompletocomofuncionatrozos
#S=spline_natural(x,xsup,ysup,True)
#I=spline_natural(x,xinf,yinf,True)
#show(plot(S)+plot(I),xmin=0,xmax=1,ymax=.4)
#spline`ssuperior
defSinf(x):
returnspline_natural(x,xinf,yinf)
#splinesinferiores
defSsup(x):
returnspline_natural(x,xsup,ysup)
graf=plot(Sinf,(0,1),color='red',linestyle='')
graf+=plot(Ssup,(0,1),color='red',linestyle='')
graf+=point(parinf,color='purple',size=30)+point(parsup,color='purple',size=30)
show(graf,ymin=.4,ymax=.4,xmin=0,xmax=1)

OtrosejemplosSpline+PolinomioInterpolador
Comprobemosquepasasinaproximamoselmismoperfialaranteriorlconpolinomiosdeinterpolacin.

#NACA2418
#interpolacionsuperior
S=interpola(x,xinf,yinf,"Nev")
#interpolacioninferior
I=interpola(x,xsup,ysup,"Nev")
graf=plot(S,color='orange')+plot(I,color='green')
graf+=plot(Sinf,(0,1),color='red',linestyle='')
graf+=plot(Ssup,(0,1),color='red',linestyle='')
graf+=point(parinf,color='purple',size=30)+point(parsup,color='purple',size=30)
show(graf,ymin=.4,ymax=.4,xmin=0,xmax=1,figsize=4)

Ejercicio
Dadoslospuntosdelasiguientetabla:
X

Obtenerunainterpolacinporsplinesascomoelpolinomiodeinterpolacin.

X=[4.,3.,2.,1.,0.,1.,2.,3.,4.]
Y=[1.,2.,1.,4.,3.,0.,1.,1.,2.]
pares=(((X[i],Y[i])foriinrange(len(X))))
defs(x):
returnspline_natural(x,X,Y)
f=interpola(x,X,Y,"Nev")
show(plot(s,4,4,color='blue',linestyle='',thickness=3)+plot(f,4,4,color='green',linestyle=':',thickness=3)+
point(pares,color='red',size=50),xmin=4,xmax=4)

Splinesyefectode"Runge"
Lautilizacindespline'sparainterpolarnoseveafectadaporelefectode"Runge".

#funciondeRUNGE
f(x)=1/(1+25*x^2)
orden=40
X=[1+i*2/(orden)foriinrange(orden+1)]
Y=[f(X[i]).n()foriinrange(orden+1)]
defs(x):
returnspline_natural(x,X,Y)
f=interpola(x,X,Y,"Nev")
#f=PR.lagrange_polynomial(zip(X,Y),algorithm="divided_difference")
graf=plot(s,X[0],X[len(X)1],color='blue',linestyle='',thickness=4)
graf+=plot(f,X[0],X[len(X)1],color='green',linestyle='',thickness=2)
graf+=point(zip(X,Y),color='red',size=50)

show(graf,xmin=X[0],xmax=X[len(X)1],ymin=5,ymax=5)

Ejemplo
Aunqueconunalineauntantoanticuadaquerepresentalasiguientefigura?

X=[0,0.2,.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10.3]
Y=[0,0.5,1,1.4,1.5,1.5,1.5,1.6,2.5,3.4,3.5,3.5,3.5,3.5,3.5,3.5,3.4,3.2,3,2.7,2,1,0]
defs(x):
returnspline_natural(x,X,Y)
Z=[0,0.2,.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10.3]
T=[0,0.8,1,1,1,.5,.2,.2,.5,1,1,1,1,1,1,.4,.1,.1,.4,1,1,.8,0]
defi(x):
returnspline_natural(x,Z,T)
graf=plot(s,0,10.3,color='blue',thickness=2)+point(zip(X,Y),color='red',size=30)
graf+=plot(i,0,10.3,color='blue',thickness=2)+point(zip(Z,T),color='red',size=30)
show(graf,xmin=0,xmax=13,ymin=1,ymax=12,figsize=6)

Ejemplo:
Losdatosdelasiguientetablaprovienendeobservacionesastronmicasdeuntipodeestrellavariabledenominadavariablecefeiday
representanmagnitudesensuvariacinaparenteconeltiempo.Obtenerunacurvadeinterpolacinenestosnodos.
X

Y 0.302

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.185

0.106

0.093

0.240

0.579

0.561

0.468

0.302

Obtenerunainterpolacinporspline'syelpolinomiodeinterpolacin

X=[0,0.2,.3,.4,.5,.6,.7,.8,1]
Y=[.302,.185,.106,.093,.240,.579,.561,.468,.302]
#PORSPLINE
s=spline_natural(x,X,Y,true)
prints
#polinomiodeinterpolacion
f=interpola(x,X,Y,"Nev")
show(plot(s,color='blue',thickness=2)+plot(f,(0,1),color='green',thickness=1)+point(zip(X,Y),color='red',
size=30),xmin=0,xmax=1.1,ymin=0,figsize=6)

Lossplinestambintienenproblemas
Observemosenelsiguienteejemplocomoseobtienenondulacionesenlosextremosdelaszonasplanasdelosdatos.Cuandolosdatosno
estnsuavizados,lainterpolacinporsplines,ansiendomejorquelapolinmica,tieneproblemas

X=[0.00,0.05,0.10,0.15,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.85,0.90,0.95,1.00]
Y=[0.00,1.00,5.00,15.00,33.50,33.00,16.50,16.00,16.00,16.00,16.00,16.00,6.00,2.00,0.0]
#porsplines
s=spline_natural(x,X,Y,true)
#polinomiodeinterpolacion
f=interpola(x,X,Y,"Nev")
show(plot(s,color='blue',thickness=2)+plot(f,
(0,1),color='green',thickness=1)+point(zip(X,Y),color='red',size=30),xmin=0,xmax=1.1,ymin=0,figsize=6)

Aprximandodatosaleatorios.
Consideremosunconjuntodepuntosaleatoriosenlaregin[0, 1]X[0, 1] dondelosnodosdelasx`sestndistribuidosuniformemente.Veaomos
comosecomprotanlossplinesyelpolinomiodeinterpolacin

numero=20

X=[i/numeroforiinrange(numero)]
Y=[random()foriinrange(numero)]
S=spline_natural(x,X,Y,true)
f=interpola(x,X,Y,"Nev")
show(plot(f,X[0],X[len(X)1],color='blue')+
point(zip(X,Y),color='red',size=30)+plot(S,color='green',thickness=2),xmin=X[0],xmax=X[len(X)1],ymin=0.5,ymax=1.5,figsize=5)

Spline'sdeunacurvaenparamtricas(aproximacindetrayectoriasenelplano)
Unrobotdebetomarunobjetosituadoenlaposicin0ydejarloenlaposicin5delrecintoesquematizadoenlafigura.Paraellorecorreuna
trayectoriadefinidaporlospuntosdelatabla,quetratandeevitarlosobstculosdelrecinto.
instante

Latrayectoriaseobtieneinterpolandolospuntosdados(x k , y k ),ymediantefuncionesa(t) yo(t) talesque(a(t), o(t))representalaposicin


delbrazoenelinstantet k = 0 5 y(a(t), o(t)) = ((t k , x k ), (t k , y k ) .Representargrficamentelatrayectoriaobtenidasia(t) yo(t) son:
1. Splinesde(t k , x k )y(t k , y k ),talesquelaaceleracininicialyfinaldelrobotsonnulas(splinenatural).
2. Polinomiosdeinterpolacinde(t k , x k )y(t k , y k ).

%hide
%auto
X=[1,1,4,4,7,7]
Y=[1,4,4,1,1,4]
graf=points(zip(X,Y),color="red",size=100)+polygon2d([[1.5,0],[1.5,4],[3.5,4],[3.5,0]],fill=true,
color='red')+polygon2d([[4.5,5],[4.5,1],[6.5,1],[6.5,5]],fill=true,color='red')+polygon2d([[0,0],[0,5],[8,5],
[8,0]],thickness=4,fill=false,color='red')
foriinrange(len(X)):
graf+=text(i,(X[i],Y[i]),color="black",fontsize=18,horizontal_alignment='right',vertical_alignment='bottom')
show(graf,xmin=1,ymax=5,xmax=9,figsize=4)

t=[0.+i/6foriinrange(6)]
X=[1,1,4,4,7,7]
Y=[1,4,4,1,1,4]
var('l')
defa(l):
returnspline_natural(l,t,X)
defo(l):
returnspline_natural(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[5]),color="blue")+points(zip(X,Y),color="red",size=150)+polygon2d([[1.5,0],
[1.5,4],[3.5,4],[3.5,0]],fill=true,color='red')+polygon2d([[4.5,5],[4.5,1],[6.5,1],[6.5,5]],fill=true,
color='red')+polygon2d([[0,0],[0,5],[8,5],[8,0]],thickness=4,fill=false,color='red'),xmin=1,ymax=5,xmax=9)
defa(l):
returnNeville(l,t,X)
defo(l):
returnNeville(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[5]),color="blue")+points(zip(X,Y),color="red",size=150)+polygon2d([[1.5,0],
[1.5,4],[3.5,4],[3.5,0]],fill=true,color='red')+polygon2d([[4.5,5],[4.5,1],[6.5,1],[6.5,5]],fill=true,
color='red')+polygon2d([[0,0],[0,5],[8,5],[8,0]],thickness=4,fill=false,color='red'),xmin=1,ymax=5,xmax=9)

PerfilAlarenparamtricas.

#PERFILALARENPARAMETRICAS
naca2418=open(DATA+'naca2418.dat')
naca2418.readline()

fromnumpyimportloadtxt
datosNACA2418=loadtxt(naca2418)
datosNACA2418=list(datosNACA2418)
par=[];Y=[];X=[]
foriinrange(len(datosNACA2418)):
par.append((datosNACA2418[i][0],datosNACA2418[i][1]))
foriinrange(len(par)):
X.append(par[i][0]*1.)
Y.append(par[i][1]*1.)
t=[i*1.foriinrange(len(X))]
var('l')
defa(l):
returnspline_natural(l,t,X)
defo(l):
returnspline_natural(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[len(X)1]),color="blue",thickness=3)+points(zip(X,Y),color="red",
size=50),xmin=0,xmax=1)

Diseoanticuadoenparmetricas.
X=[0,0.2,.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10.3]
Y=[0,0.5,1,1.4,1.5,1.5,1.5,1.6,2.5,3.4,3.5,3.5,3.5,3.5,3.5,3.5,3.4,3.2,3,2.7,2,1,0]
Z=[0,0.2,.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10.3]
Z.reverse()
T=[0,0.8,1,1,1,.5,.2,.2,.5,1,1,1,1,1,1,.4,.1,.1,.4,1,1,.8,0]
T.reverse()
foriinrange(len(Z)):
X.append(Z[i])
Y.append(T[i])
t=[iforiinrange(len(X))]
var('l')
defa(l):
returnspline_natural(l,t,X)
defo(l):
returnspline_natural(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[len(X)1]),color="blue",thickness=2)+points(zip(X,Y),color="red",
size=30),xmin=0,xmax=11)

AproximacindelaCardioide(curvaplana)enparmetricasporsplinesypolinomios
#CARDIOIDE
xt(x)=cos(x)*(1+cos(x))
yt(x)=sin(x)*(1+cos(x))
orden=20
t=[0.+i*2.*n(pi)/(orden1)foriinrange(orden)]
X=[xt(t[i]).n()foriinrange(orden)]
Y=[yt(t[i]).n()foriinrange(orden)]
var('l,m')
defa(l):
returnspline_natural(l,t,X)
defo(l):
returnspline_natural(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[len(t)1]),color=hue(0.3))+points(zip(X,Y),color="red"))
defa(l):
returnNeville(l,t,X)
defo(l):
returnNeville(l,t,Y)
show(parametric_plot((a,o),(l,t[0],t[len(t)1]),color=hue(0.3))+points(zip(X,Y),color="red"))

Potrebbero piacerti anche