-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpolacion.tex
1756 lines (1487 loc) · 129 KB
/
interpolacion.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Interpolación y ajuste de funciones}\label{interpolacion}
\chaptermark{Interp. y ajust. funciones. \textreferencemark\ Interp. \& funct fitting}
\epigraph{Digo que ya tú sabes que la humildad es la basa y fundamento de todas las virtudes, y que sin ella no hay alguna que lo sea. Ella allana inconvenientes, vence dificultades, y es un medio que siempre a gloriosos fines nos conduce; de los enemigos hace amigos, templa la cólera de los airados y menoscaba la arrogancia de los soberbios; es madre de la modestia y hermana de la templanza; en fin, con ella no pueden atravesar triunfo que les sea de provecho los vicios, porque en su blandura y mansedumbre se embotan y despuntan las flechas de los pecados.}{El coloquio de los perros. Miguel de Cervantes}
\begin{paracol}{2}
En este capítulo vamos a estudiar distintos métodos de aproximación polinómica. En términos generales el problema consiste en sustituir una función $f(x)$ por un polinomio,
\switchcolumn
In this chapter, we will explore different methods of polynomial approximation. We can define the problem in general terms as finding a polynomial to represent a function $f(x)$.
\end{paracol}
\begin{equation*}
f(x)\approx p(x)=a_0+a_1\cdot x+a_2\cdot x^2+a_3\cdot x^3+\cdots +a_n \cdot x^n
\end{equation*}
\begin{paracol}{2}
Para obtener la aproximación podemos partir de la ecuación que define $f(x)$, por ejemplo la función error,
\switchcolumn
To obtain the approximation, we can start from the equation that defines $f(x)$, for instance, the error function,
\end{paracol}
\begin{equation*}
erf(x)=\frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2}dt
\end{equation*}
\begin{paracol}{2}
O bien, puede suceder que solo conozcamos algunos valores de la función, por ejemplo a través de una tabla de datos,
\switchcolumn
Nevertheless, it is possible that we only have some values of the function, such as when we only have a data table.
\end{paracol}
\begin{table}[h]
\caption{$f(x)=erf(x)$}
\centering
\begin{tabular}{c|c}
$x$&$f(x)$\\
\hline
$0.0$& $0.0000$\\
$0.1$&$0.1125$\\
$0.2$&$0.2227$\\
$0.3$&$0.3286$\\
$0.4$&$0.4284$\\
$0.5$&$0.5205$\\
\end{tabular}
\label{tpuntos2}
\end{table}
\begin{paracol}{2}
La aproximación de una función por un polinomio, tiene ventajas e inconvenientes.
Probablemente la principal ventaja, desde el punto de vista del cómputo, es que un polinomio es fácil de evaluar mediante un ordenador ya que solo involucra operaciones aritméticas sencillas. Además, los polinomios son fáciles de derivar e integrar, dando lugar a otros polinomios.
En cuanto a los inconvenientes hay que citar el crecimiento hacia infinito o menos infinito de cualquier polinomio para valores de la variable independiente alejados del origen. Esto puede dar lugar en algunos casos a errores de redondeo difíciles de manejar, haciendo muy difícil la aproximación para funciones no crecientes.
Vamos a estudiar tres métodos distintos; en primer lugar veremos la aproximación mediante el polinomio de Taylor, útil para aproximar una función en las inmediaciones de un punto. A continuación, veremos la interpolación polinómica y, por último, estudiaremos el ajuste polinómico por mínimos cuadrados.
El uso de uno u otro de estos métodos esta asociado a la información disponible sobre la función que se desea aproximar y al uso que se pretenda hacer de la aproximación realizada.
\section{El polinomio de Taylor.}\index{Polinomio de Taylor}
\sectionmark{El polinomio de Taylor \textreferencemark\ Taylor's polynomial}
Supongamos una función infinitamente derivable en un entorno de un punto $x_0$. Su expansión en serie de Taylor se define como,
\switchcolumn
To approximate a function using a polynomial has pros and cons.
Perhaps the main advantage, from a computing point of view, is that a polynomial is easy to evaluate using a computer as it only involves simple arithmetical operations. Besides, Polynomial integration and derivation are operations that are easy to carry out, yielding other polynomials.
Among their drawbacks we have to remark the polynomial growing towards infinity or minus infinity as the independent variable goes away zero. This can give rise in some cases to rounding errors that are difficult to handle, making the approximation for non-increasing functions very difficult.
We will study three different methods: first we will see the approximation using the Taylor polynomial, very useful to approximate a function close to a point for which we know the function value. Later, we will discus polynomial interpolation and finally we present mean square polynomial fitting.
We may relate the use of one or another method to the available information on the function we want to approximate and to the objectives we want to reach with the approximation.
\section{The Taylor's polynomi\-al.}\index[eng]{Taylor's polynomial}
Suppose we have an function infinitely derivable around a point $x_0$. We define the function taylor series expansion as,
\end{paracol}
\begin{equation*}
f(x)=f(x_0)+f'(x_0)\cdot (x-x_0)+\frac{1}{2} f''(x_0)\cdot (x-x_0)^2+\cdots + \frac{1}{n!}f^{(n)}(x_0)\cdot (x-x_0)^n+ \frac{1}{(n+1)!}f^{(n+1)}(z)\cdot (x-x_0)^{n+1}
\end{equation*}
\begin{paracol}{2}
Donde $z$ es un punto sin determinar situado entre $x$ y $x_0$. Si eliminamos el último término, la función puede aproximarse por un polinomio de grado $n$
\switchcolumn
Where $z$ is an indeterminate point located between $x$ and $x_0$. If we eliminate the last term the function would be approximated by a degree $n$ polynomial.
\end{paracol}
\begin{equation*}
f(x)\approx f(x_0)+f'(x_0)\cdot (x-x_0)+\frac{1}{2}f''(x_0)\cdot (x-x_0)^2+\cdots + \frac{1}{n!}f^{(n)}(x_0)\cdot (x-x_0)^n
\end{equation*}
\begin{paracol}{2}
El error cometido al aproximar una función por un polinomio de Taylor de grado $n$, viene dado por el término,
\index{Polinomio de Taylor! Error de la aproximación}
\switchcolumn
The error we get when approximating a function by a degree $n$ Taylor polynomial can be obtained as,
\end{paracol}
\begin{equation*}
e(x)=\lvert f(x) -p(x)\rvert=\left\lvert\frac{1}{(n+1)!} f^{(n+1)}(z)\cdot (x-x_0)^{n+1}\right\rvert
\end{equation*}
\begin{paracol}{2}
Es fácil deducir de la ecuación que el error disminuye con el grado del polinomio empleado y aumenta con la distancia entre $x$ y $x_0$. Además cuanto más suave es la función (derivadas pequeñas) mejor es la aproximación.
Por ejemplo para la función exponencial, el polinomio de Taylor de orden $n$ desarrollado en torno al punto $x_0=0$ es, \index{Polinomio de Taylor! Serie de la función exponencial}
\switchcolumn
Looking at the error function, it is easy to realize that decreases when the polynomial degree increases and increases when the distance between $x$ and $x_0$ increases.
For instance, the Taylor polynomial of degree $n$ for the exponential functions, around the point $x_0=0$ is, \index[eng]{Taylor Polynomial! Series expansion for the exponential function}
\end{paracol}
\begin{equation*}
e^x\approx 1+x+\frac{1}{2}x^2+\cdots+\frac{1}{n!}x^n=\sum_{i=0}^n\frac{1}{i!}x^i
\end{equation*}
\begin{paracol}{2}
y el del logaritmo natural, desarrollado en torno al punto $x_0=1$, \index{Polinomio de Taylor! Serie del logaritmo natural}
\switchcolumn
and the Taylor polynomial for the logarithm, around the point $x-= =1$ is, \index{Taylor polynomial for the logaritm function}
\end{paracol}
\begin{equation*}
\log(x)\approx (x-1)-\frac{1}{2}(x-1)^2+\cdots+\frac{(-1)^{n+1}}{n}(x-1)^n=\sum_{i=1}^n\frac{(-1)^{i+1}}{i}(x-1)^i
\end{equation*}
\begin{paracol}{2}
La existencia de un término general para los desarrollos de Taylor de muchas funciones elementales lo hace particularmente atractivo para aproximar funciones mediante un ordenador. Así por ejemplo, la siguiente función escrita en Python, aproxima el valor del logaritmo natural en un punto, empleando un polinomio de Taylor del grado que se desee,
\switchcolumn
The existence of a general term for Taylor's expansion of many essential functions makes it highly interesting to approximate functions using a computer. For example, the following function, written in Python, approximates the natural logarithm using Taylor's polynomial of any degree we want.
\end{paracol}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=series\_de\_taylor.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/series_de_taylor.py}
\begin{paracol}{2}
La aproximación funciona razonablemente bien para puntos comprendidos en el intervalo $0<x<2$. La figura \ref{fig:ln} muestra los resultados obtenidos en dicho intervalo para polinomios de Taylor del logaritmo natural de grados 2, 5, 10 20. La linea continua azul representa el valor del logaritmo obtenido con la función de Numpy \mintinline{python}{log}.
\switchcolumn
The approximation works reasonably well for points inside the interval $0<x<2$. Figure \ref{fig:ln} shows the results achieved inside such interval, using Taylor's polynomial with degrees 2, 5, 10 and 20. The blue line represent the logarithm values we get using the numpy function \mintinline{python}{log}.
\end{paracol}
\begin{figure}[h]
\centering
\includegraphics[width=10cm]{ln.eps}
\bicaption{Comparación entre resultados obtenidos para polinomios de Taylor del logaritmo natural. (grados 2, 3, 5, 10, 20)}{A comparison among the results achieved using Taylor polynomials to approach the logarithm. (2, 3, 5, 10, 20 degrees) }
\label{fig:ln}
\end{figure}
\begin{paracol}{2}
\index{Polinomio de Taylor! Series de las funciones seno y coseno}
Las funciones $\sin(x)$ y $\cos(x)$, son también simples de aproximar mediante polinomios de Taylor. Si desarrollamos en torno a $x_0=0$, la serie del coseno solo tendrá potencias pares mientras que la del seno solo tendrá potencias impares,
\switchcolumn
\index[eng]{Tailor's polynomial! Sine and consine function expansion.} Functions $\sin(x)$ and $\cos(x)$, are also easy to approach using Taylor's polynomials. If we expand around $x_0=0$, the cosine series will have only even powers and the sine series will only have odd powers,
\end{paracol}
\begin{align*}
\cos(x)&\approx \sum_{i=0}^n \frac{(-1)^i}{(2i)!}x^{2i}\\
\sin(x)&\approx \sum_{i=0}^n \frac{(-1)^i}{(2i+1)!}x^{2i+1}
\end{align*}
\begin{figure}
\centering
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=10.5cm]{cos.eps}
\bicaption{$\cos(x)$, polinomios 2, 4, 6 y 8 grados}{polynomials 2, 4, 6 and 8 degrees}\label{fig:cos}
\end{subfigure}
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=10.5cm]{sin.eps}
\bicaption{$\sin(x)$, polinomios 3, 5, 7 y 9 grados}{polynomials 2, 4, 6 and 8 degrees} \label{fig:sin}
\end{subfigure}
\bicaption{Polynomios de Taylor para las funciones coseno y seno}{Taylor polynomial for cosine and sine functions}
\end{figure}
\begin{paracol}{2}
En las figuras \ref{fig:cos} y \ref{fig:sin} Se muestran las aproximaciones mediante polinomios de Taylor de las funciones coseno y seno. Para el coseno se han empleado polinomios hasta grado 8 y para el seno hasta grado 9. En ambos casos se dan los resultados correspondientes a un periodo $(-\pi, \pi)$. Si se comparan los resultados con las funciones \texttt{cos} y \texttt{sin}, suministradas por Numpy, puede observarse que la aproximación es bastante buena para los polinomios de mayor grado empleados en cada caso.
\section{Interpolación polinómica.}
\sectionmark{Interpolación polinómica \textreferencemark\ Polynomial interpolation}
Se entiende por interpolación el proceso por el cual, dado un conjunto de pares de puntos $(x_0,y_0),(x_1,y_1),\cdots (x_n,y_n)$ se obtiene una función $f(x)$, tal que, $y_i=f(x_i)$, para cada par de puntos $(x_i,y_i)$ del conjunto. Si, en particular, la función empleada es un polinomio $f(x)\equiv p(x)$, entonces se trata de interpolación polinómica. \index{Interpolación! Polinómica}
\paragraph{Teorema de unicidad.} Dado un conjunto \index{Interpolación! Teorema de unicidad} $(x_0,y_0),(x_1,y_1),\cdots (x_n,y_n)$ de $n+1$ pares de puntos, tales que todos los valores $x_i$ de dicho conjuntos son diferentes entre sí, solo existe un polinomio $p(x)$ de grado $n$, tal que $y_i=p(x_i)$ para todos los pares de puntos del conjunto.
Si tratamos de interpolar los puntos con un polinomio de grado menor que $n$, es posible que no encontremos ninguno que pase por todos los puntos. Si, por el contrario empleamos un polinomio de grado mayor que $n$, nos encontramos con que no es único. Por último si el polinomio empleado es de grado $n$, entonces será siempre el mismo con independencia del método que empleemos para construirlo.
\subsection{La matriz de Vandermonde} \index{Matriz de Vandermonde}
Supongamos que tenemos un conjunto de pares de puntos $\mathcal{A}$,
\switchcolumn
Figures \ref{fig:cos} and \ref{fig:sin} show aproximations to sine and consine functions using Taylor's polynomials. We have use polynomias up to 8DWM1001 degree for the cosine function and up to degree 9 for the sine function. In both cases we have calculated the results inside the interval $(-\pi, \pi)$. When we compare these results with those yielded by Numpy functions \mintinline{python}{cos} and \mintinline{python}{sin}, we see that the approximation is quite good for the higher degree polynomials we have used in each case.
\section{Polynomial interpolati\-on.}
\sectionmark{Interpolación polinómica \textreferencemark\ Polynomial interpolation}
We define the interpolation as a process that, departing from a set of data pairs \\ $(x_0,y_0),(x_1,y_1), \cdots (x_n,y_n)$, allows us to find a function $f(x)$ such that $y_i = f(x_i)$ for all pairs $(x_i,y_i)$ of the set. In the case we use a polynomial as the interpolating function $f(x)\equiv p(x)$, we denote it as polynomial Interpolation. \index{Interpolation! Polynomial}
\paragraph{The interpolation theorem.}\index[eng]{Interpolation! Interpolation theorem}
For any set of $n+1$ pairs of data points\\ $(x_0,y_0) ,(x_1,y_1),\cdots (x_n,y_n)$ , where no two $x_i$ are the same, there is one and only one polynomial $p(x)$ of degree $n$ that interpolates these points, i.e, it satisfies that $y_i=p(x_i)$ for all pairs on the dataset.
If we try to interpolate the points with a polynomial whose degree is less than $n$, it is possible that we will not find one that fits all the pairs in the dataset. Conversely, if we try to use a polynomial with a degree greater than $n$, it will not unique. Eventually, if we use a degree $n$ polynomial, this polynomial is always the same regardless method used to build it.
\subsection{The Vandermonde's matrix}\index[eng]{Intrpolation! Vandermonde's matrix}
Suppose we have a set $\mathcal{A}$ of data points.
\end{paracol}
\begin{table}[h]
%\caption{$f(x)=erf(x)$}
\centering
\begin{tabular}{c|c}
$x$&$f(x)$\\
\hline
$x_0$& $y_0$\\
$x_1$&$y_1$\\
$x_2$&$y_2$\\
$\vdots$&$\vdots$\\
$x_n$&$y_n$
\end{tabular}
\label{tpuntos3}
\end{table}
\begin{paracol}{2}
Para que un polinomio de orden $n$,
\switchcolumn
For a polynomial of degree $n$,
\end{paracol}
\begin{equation*}
p(x)=a_0+a_1x+a_2x^2+\cdots+a_nx^n
\end{equation*}
\begin{paracol}{2}
pase por todos los pares de $\mathcal{A}$ debe cumplir,
\switchcolumn
to go through all pairs in $\mathcal{A}$, it must satisfy,
\end{paracol}
\begin{equation*}
y_i=a_0+a_1x_i+a_2x_i^2+\cdots+a_nx_i^n, \ \forall (x_i,y_i) \in \mathcal{A}
\end{equation*}
\begin{paracol}{2}
Es decir, obtendríamos un sistema de $n$ ecuaciones lineales, una para cada par de valores, en la que las incógnitas son precisamente los $n+1$ coeficientes $a_i$ del polinomio.
Por ejemplo para los puntos,
\switchcolumn
So, we would have a system of $n$ linear equations, one for each pair of data points, where the unknowns are the $n+1$ coefficients $a_i$ of the polynomial.
for example, for the dataset,
\end{paracol}
\begin{table}[h]
%\caption{$f(x)=erf(x)$}
\centering
\begin{tabular}{c|c}
$x$&$f(x)$\\
\hline
$1$&$\ 2$\\
$2$&$ \ 1$\\
$3$&$-2$
\end{tabular}
\label{tpuntos4}
\end{table}
\begin{paracol}{2}
Obtendríamos,
\switchcolumn
we get,
\end{paracol}
\begin{align*}
a_0+a_1\cdot 1+ a_2\cdot 1^2&=2\\
a_0+a_1\cdot 2+ a_2\cdot 2^2&=1\\
a_0+a_1\cdot 3+ a_2\cdot 3^2&=-2
\end{align*}
\begin{paracol}{2}
que podríamos expresar en forma matricial como,
\switchcolumn
which we can express in matrix form as,
\end{paracol}
\begin{equation*}
\begin{pmatrix}
1&1&1^2\\
1&2&2^2\\
1&3&3^2
\end{pmatrix}\cdot \begin{pmatrix}
a_0\\
a_1\\
a_2
\end{pmatrix}=\begin{pmatrix}
2\\
1\\
-2
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
Y en general, para $n$ pares de datos,
\switchcolumn
And, in general, for $n$ data pairs,
\end{paracol}
\begin{equation*}
\begin{pmatrix}
1&x_0&x_0^2&\cdots &x_0^n\\
1&x_1&x_1^2&\cdots &x_1^n\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
1&x_n&x_n^2&\cdots &x_n^n
\end{pmatrix}\cdot \begin{pmatrix}
a_0\\
a_1\\
\vdots\\
a_n
\end{pmatrix}=\begin{pmatrix}
y_0\\
y_1\\
\vdots\\
y_n
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
La matriz de coeficientes del sistema resultante recibe el nombre de matriz de Vandermonde. Está formada por la $n$ primeras potencias de cada uno de los valores de la variable independiente, colocados por filas. Es evidente que cuanto mayor es el número de datos, mayor tenderá a ser la diferencia de tamaño entre los elementos de cada fila. Por ello, en la mayoría de los casos, resulta ser una matriz mal condicionada para resolver el sistema numéricamente. En la práctica, para obtener el polinomio interpolador, se emplean otros métodos alternativos,
\subsection{El polinomio interpolador de Lagrange.} \label{sec:lagranje}\index{Interpolación! Polinomio de Lagrange} \index{Polinomio de Lagrange}
A partir de los valores $x_0, x_1,\cdots, x_n$, se construye el siguiente conjunto de $n+1$ polinomios de grado $n$
\switchcolumn
The coefficient matrix of the resulting system is called the Vandermonde's matrix. Its elements are hte $n$ first powers of the independent variable values, allocated by rows. It is easy to notice that when the number of data increases the difference among the elements of a row will tend to increase also. For this reason in most cases the Vandermonde's matrix is a poor conditioned matrix and so not suitable for solving the system numerically. For this reason, in practice,the interpolation polynomial is computed using other alternative methods.
\subsection{Lagrange Interpolating Polynomial}\index[eng]{Interpolation!Lagrange Polynomial} \index[eng]{Lagrange Polynomial}
Departing from the values $x_0,x_1,\cdots,x_n$, We build the following set of $n+1$ polynomial of degree $n$
\end{paracol}
\begin{equation*}
l_j(x)=\prod_{\substack{k=0\\
k\neq j}}^n\frac{x-x_k}{x_j-x_k}=\frac{(x-x_0)(x-x_1)\cdots(x-x_{j-1})(x-x_{j+1})\cdots(x-x_n)}{(x_j-x_0)(x_j-x_1)\cdots(x_j-x_{j-1})(x_j-x_{j+1})\cdots(x_j-x_n)}
\end{equation*}
\begin{paracol}{2}
Los polinomios así definidos cumplen una interesante propiedad en relación con los valores $x_0, x_1,\cdots, x_n$, empleados para construirlos,
\switchcolumn
These polynomial exhibit an interesting property when evaluated at the points $x_0, x_1,\cdots, x_n$, we have used for building them.
\end{paracol}
\begin{equation*}
l_j(x_i)= \left\{
\begin{aligned}
1,\ i=j\\
0,\ i\neq j
\end{aligned}
\right.
\end{equation*}
\begin{paracol}{2}
A partir de estos polinomios podemos construir ahora el siguiente polinomio de interpolación empleando las imágenes $y_0,y_1\cdots, y_n$ correspondientes a los valores $x_0, x_1,\cdots, x_n$,
\switchcolumn
From this polynomials we can build a interporlation polynomial using the codomain values $y_0,y_1\cdots, y_n$ corresponding to the domain values $x_0, x_1,\cdots, x_n$,
\end{paracol}
\begin{equation*}
p(x)=\sum_{j=0}^n l_j(x)\cdot y_j
\end{equation*}
\begin{paracol}{2}
Efectivamente, es fácil comprobar que, tal y como se ha construido, este polinomio pasa por los pares de puntos $x_i,y_i$, puesto que $p(x_i)=y_i$.
El siguiente código de en Python calcula el valor en un punto x cualquiera del polinomio de interpolación de Lagrange construido a partir un conjunto de puntos $\mathcal{A}\equiv \{(x_i,y_i)\}$.
\switchcolumn
It is ease to check that, using this method for building the interpolation polynomial, it passes through all pairs of points $x_i,y_i$, because $p(x_i)=y_i$.
The following python function \mintinline{python}{lagrang} calculates, at any point x, the Lagrange interpolating polynomial value built from a set of pairs of points $\mathcal{A}\equiv \{(x_i,y_i)\}$.
\end{paracol}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=lgr\_pol.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/lgr_pol.py}
\begin{paracol}{2}
\subsection{Diferencias divididas.}\label{sec:difdiv} \index{Interpolación! Diferencias Divididas} \index{Diferencias Divididas}
Tanto el método de la matriz de Vandermonde como el de los polinomios de Lagrange, presentan el inconveniente de que si se añade un dato más $(x_{n+1}, y_{n+1})$ a la colección de datos ya existentes, es preciso recalcular el polinomio de interpolación desde el principio.
El método de las diferencias divididas, permite obtener el polinomio de interpolación en un número menor de operaciones que en el caso del polinomio de Lagrange y además, el cálculo se hace escalonadamente, aprovechando todos los resultados anteriores cuando se añade al polinomio la contribución de un nuevo dato.
El polinomio de orden $n$ de diferencias divididas se construye de la siguiente manera,
\switchcolumn
\subsection{Divided diferences.}\index{Interpolation! Divided diferences} \index{Divided diferences}
The two method we have studied so far, Vadermonde matrix and Lagrange polynomial, have a common drawback. If we add a new pair of data $(x_{n+1},y_{n+1})$ to the existing data collection, it is necessary to recalculate the interpolation polynomial from scratch.
The divided differences algorithm allows us to build the interpolation polynomial performing less operations than in the case of Lagrange polynomial. Besides, the computing is carried out stepwise, making use of all previous results when a new data pair is added to calculate the interpolation polynomial.
We build the divided differences polynomial of degree $n$ as follows,
\end{paracol}
\begin{equation*}
p_n(x)=a_0+(x-x_0)\cdot a_1+(x-x_0)\cdot (x-x_1)\cdot a_2+\cdots +(x-x_0)\cdot (x-x_1)\cdots (x-x_{n-2})\cdot(x-x_{n-1})\cdot a_n
\end{equation*}
\begin{paracol}{2}
Donde, $(x_0, y_0), (x_1,y_1), \cdots (x_n, y_n)$, representan los datos para los que se quiere calcular el polinomio interpolador de grado $n$. Si sustituimos las datos en el polinomio, llegamos a un sistema de ecuaciones, triangular inferior, en el que las incógnitas son los coeficientes del polinomio.
\switchcolumn
Where $(x_0, y_0), (x_1,y_1), \cdots (x_n, y_n)$, represent the dataset for which we want to calculate the interpolation polynomial of degree $n$. If we evaluate the polynomial using the dataset we arrive to a lower triangular system of linear equation, where the polynomial coefficients are the unknowns.
\end{paracol}
\begin{align*}
a_0&&=y_0\\
a_0&+(x_1-x_0)a_1&=y_1\\
a_0&+(x_2-x_0)a_1+(x_2-x_0)(x_2-x_1)a_2&=y_2\\
\cdots\\
a_0&+(x_n-x_0)a_1+\cdots+(x_n-x_0)(x_n-x_1)\cdots (x_n-x_{n-2})(x_n-x_{n-1})a_n&=y_n
\end{align*}
\begin{paracol}{2}
Este sistema se resuelve explícitamente empleando un esquema de diferencias divididas.
La diferencia divida de primer orden entre dos puntos $(x_0,y_0)$ y $(x_1,y_1)$ se define como,
\switchcolumn
This system can be solved using the divided differences algorithm.
We define the first-order two-point divided difference $(x_0,y_0)$ y $(x_1,y_1)$ as,
\end{paracol}
\begin{equation*}
f\left[x_0,x_1\right]=\frac{y_1-y_0}{x_1-x_0}
\end{equation*}
\begin{paracol}{2}
Para tres puntos, $(x_0,y_0)$, $(x_1,y_1)$ y $(x_2,y_2)$, se define la diferencia dividida de segundo orden como,
\switchcolumn
For three point, $(x_0,y_0)$, $(x_1,y_1)$ y $(x_2,y_2)$, we define the second-order divided difference as,
\end{paracol}
\begin{equation*}
f\left[x_0,x_1,x_2\right]=\frac{f\left[x_1,x_2\right]-f\left[x_0,x_1\right]}{x_2-x_0}
\end{equation*}
\begin{paracol}{2}
y, en general definiremos la diferencia dividida de orden $i$ para $i+1$ puntos como,
\switchcolumn
and eventually, we can define the $i-\text{order}$ divide diference for $i+1$ points as,
\end{paracol}
\begin{equation*}
f\left[x_0,x_1,\cdots,x_i\right]=\frac{f\left[x_1,x_2,\cdots,x_i\right]-f\left[x_0,x_1,\cdots,x_{i-1}\right]}{x_i-x_0}
\end{equation*} \begin{paracol}{2}
Si despejamos por sustitución progresiva los coeficientes del polinomio de interpolación del sistema triangular inferior obtenido, cada coeficiente puede asociarse a una diferencia dividida,
\switchcolumn
We can now get the polynomial coefficients applying progressive substitutions to the lower triangular system defined above, then, each coefficient may be related with a divided difference,
\end{paracol}
\begin{align*}
a_0&=f\left[x_0\right]=y_0\\
a_1&=f\left[x_0,x_1\right]\\
\vdots\\
a_i&=f\left[x_0,x_1,\cdots,x_i\right]\\
\vdots\\
a_n&=f\left[x_0,x_1,\cdots,x_n\right]\\
\end{align*} \begin{paracol}{2}
Por tanto, podemos obtener directamente los coeficientes del polinomio calculando las diferencias divididas. Veamos un ejemplo empleando el siguiente conjunto de cuatro datos,
\switchcolumn
Therefore we can get the polynomial coefficients straightforwardly if we compute the divided differences. Let's see an example using the following four data set.
\end{paracol}
\begin{table}[h]
\centering
\begin{tabular}{c|cccc}
x&0&1&3&4\\
\hline
y&1&-1&2&3
\end{tabular}
\end{table}
\begin{paracol}{2}
Habitualmente, se construye a partir de los datos una tabla, como la \ref{tabdif}, de diferencias divididas. Las primera columna contiene los valores de la variable $x$, la siguiente los valores de las diferencias divididas de orden cero (valores de $y$). A partir de la segunda, las siguientes columnas contienen las diferencias dividas de los elementos de la columna anterior, calculados entre los elementos que ocupan filas consecutivas. La tabla va perdiendo cada vez una fila, hasta llegar a la diferencia dividida de orden $n-1$ de todos los datos iniciales.
\switchcolumn
Usually, we build the divided difference polynomial, using a table such as table \ref{tabdif}. the first column contains the values of variable $x$ the second the values of the cero-order divided differences (values of variable $y$). From the second one on, the following columns contain the divided differences of the elements held in the previous column. These differences are calculated using the elements located on consecutive rows. The table lost a row each time we advance a column. When we arrive to the $n-1$-order divided difference, we have a single value that depends on all initial data.
\end{paracol}
\begin{table}[h]
\centering
\bicaption{Tabla de diferencia divididas para cuatro datos}{four data divided difference table}
\begin{tabular}{ccccc}
$x_i$&$y_i$&$f\left[x_i,x_{i+1}\right]$&$f\left[x_i,x_{i+1},x_{i+2}\right]$&$f\left[x_i,x_{i+1},x_{i+2},x_{i+3}\right]$\\
\hline
$x_0=0$&$y_0=\ \ 1$&$f\left[x_0,x_1\right]=-2$&$f\left[x_0,x_1,x_2\right]=\ \ 7/6$&$f\left[x_0,x_1,x_2,x_3\right]=-1/3$\\
$x_1=1$&$y_1=-1$&$f\left[x_1,x_2\right]=3/2$&$f\left[x_1,x_2,x_3\right]=-1/6$\\
$x_2=3$&$y_2=\ \ 2$&$f\left[x_2,x_3\right]=\ \ 1$\\
$x_3=4$&$y_3=\ \ 3$\\
\end{tabular}
\label{tabdif}
\end{table}
\begin{paracol}{2}
Los coeficientes del polinomio de diferencias divididas se corresponden con los elementos de la primera fila de la tabla. Por lo que en nuestro ejemplo el polinomio resultante sería,
\switchcolumn
The divided differences polynomial coefficients are the elements held in the first row of the table. So, for our example, we obtain the following interpolation polynomial,
\end{paracol}
\begin{equation*}
p_3(x)=1-2x+\frac{7}{6}x(x-1)-\frac{1}{3}x(x-1)(x-3)
\end{equation*}
\begin{paracol}{2}
Es importante hacer notar que el polinomio de interpolación obtenido por diferencias divididas siempre aparece representado como suma de productos de binomios $(x-x_0)(x-x_1)\cdots$ y los coeficientes obtenidos corresponden a esta representación y no a la representación habitual de un polinomio como suma de potencias de la variable $x$.
El siguiente código permite calcular el polinomio de diferencias divididas a partir de un conjunto de $n$ datos. Como el polinomio de diferencias divididas toma una forma especial, es preciso tenerlo en cuenta a la hora de calcular su valor en un punto $x$ determinado. La función \mintinline{python}{difdiv} permite obtener los coeficientes del polinomio de diferencias divididas a partir de una coleccion de datos $x,y$. La función \mintinline{python}{evdif} permite calcular el valor que toma el polinomio en un punto cualquiera $x_i$, a partir de los coeficientes calculados y los valores $x$ de la collección de datos.
\switchcolumn
Notice that the interpolation polynomial, built using divided differences, it always represented as a sum of binomials products $(x-x_0)(x-x_1)\cdots$ and the coefficients computed belong to this representation a not to the standard polynomial representation as a sum of variable $x$ powers.
The following code implement the divided differences polynomial from a set of $n$ data. We must take into account the special form of the polynomial to calculate the value ot takes in an specific $x$ point. Function \mintinline{python}{difdiv} computes the polynomiañ coefficients departing from a set $x,y$ of data. Function \mintinline{python}{evdif} calculates the value of the polynomial in a point whatsoever, using the computed coefficientes and the $x$ values of the data set.
\end{paracol}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=dif\_div.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/dif_div.py}
\begin{paracol}{2}
\subsection{El polinomio de Newton-Gregory} \label{sec:newgre} \index{Interpolación!Polinomio de Newton-Gregory} \index{Polinomio de Newton-Gregory}
Supone una simplificación al cálculo del polinomio de diferencias divididas para el caso particular en que los datos se encuentran equiespaciados y dispuestos en orden creciente con respecto a los valores de la coordenada $x$.
En este caso, calcular los valores de las diferencias es mucho mas sencillo. Si pensamos en las diferencias de primer orden, los denominadores de todas ellas son iguales, puesto que los datos están equiespaciados,
\switchcolumn
\subsection{The Newton-Gregory polynomial}\index[eng]{Interpolation!The Newton-Gregory polynomial}\index[eng]{The Newton-Gregory polynomial}
This polynomial is a simplification of the divided difference polynomial for the case in which the $x$ data of the data set are equispaced and increasingly ordered.
For this case, it is much easier to compute the values of the differences. Think, for instance, in the first-order differences, as far as the data are equispaced ll denominators are equal,
\end{paracol}
\begin{equation*}
\Delta x \equiv x_i-x_{i-1} =h
\end{equation*}
\begin{paracol}{2}
En cuanto a los numeradores, se calcularían de modo análogo al de las diferencias divididas normales,
\switchcolumn
Concerning the numerators, they are computed as in the standard case of divided differences,
\end{paracol}
\begin{equation*}
\Delta y_0= y_1-y_0, \Delta y_1=y_2-y_1, \cdots, \Delta y_i=y_{i+1}-y_i, \cdots, \Delta y_{n-1}=y_{n}-y_{n-1}
\end{equation*}
\begin{paracol}{2}
Las diferencias de orden superior para los numeradores se pueden obtener de modo recursivo, a partir de las de orden uno, puesto que los denominadores de todas ellas $h$, son iguales.
\switchcolumn
Higher order differences can be computed recursively from the first-order differences because the denominator of them all, $h$ are equal.
\end{paracol}
\begin{equation*}
\Delta^2 y_0=\Delta \left(\Delta y_0 \right) =(y_2-y_1)-(y_1-y_0)=(y_2-2y_1+y_0)
\end{equation*}
\begin{paracol}{2}
En este caso, el denominador de la diferencia sería $x_2-x_0=2h$, y la diferencia tomaría la forma,
\switchcolumn
In this case, the difference denominator would be $x_2-x_0=2h$, and the difference would take the form,
\end{paracol}
\begin{equation*}
f[x_0,x_1,x_2]=\frac{\Delta^2y_0}{2h^2}
\end{equation*}
\begin{paracol}{2}
En general, para la diferencias de orden n tendríamos,
\switchcolumn
In genral, for the order-n differences we obtain,
\end{paracol}
\begin{equation*}
\Delta^n y_0=y_n-\binom{n}{1}\cdot y_{n-1}+\binom{n}{2}\cdot y_{n-2}-\cdots+(-1)^n\cdot y_0
\end{equation*}
\begin{paracol}{2}
Donde se ha hecho uso de la expresión binomial,
\switchcolumn
Where we have used the binomial expression,
\end{paracol}
\begin{equation*}
\binom{k}{l}=\frac{k!}{l!\cdot(k-l)!}
\end{equation*}
\begin{paracol}{2}
Para obtener la diferencia dividida de orden n, bastaría ahora dividir por $n!\cdot h^n$.
\switchcolumn
And, eventually, we obtain the order-n divided difference just dividing by $n!\cdot h^n$.
\end{paracol}
\begin{equation*}
f\left[x_0,x_1,\cdots,x_n\right]=\frac{\Delta^n y_0}{n!\cdot h^n}
\end{equation*}
\begin{paracol}{2}
A partir de las diferencias, podemos representar el polinomio de diferencias divididas resultante como,
\switchcolumn
Once we have got the differences we can write the divided differences polynomial as,
\end{paracol}
\begin{equation*}
p_n(x)=y_0+\frac{x-x_0}{h}\Delta y_0+\frac{(x-x_1)\cdot (x-x_0)}{2\cdot h^2}\Delta^2 y_0+\cdots +\frac{(x-x_{n-1}) \cdots (x-x_1)\cdot (x-x_0)}{n! \cdot h^n}\Delta^n y_0
\end{equation*}
\begin{paracol}{2}
Este polinomio se conoce como el polinomio de Newton-Gregory, y podría considerarse como una aproximación numérica al polinomio de Taylor de orden n de la posible función asociada a los datos empleados.
En este caso, podríamos construir la tabla para obtener los coeficientes del polinomio, calculando en cada columna simplemente las diferencias de los elementos de la columna anterior. Por ejemplo,
\switchcolumn
This polynomial is known as the Newton-Gregory polynomial, and it could be considered as a numerical approximation to the n-degree Taylor polynomial of the (possible) function associated to the dataset.
In this case, we can build the table to obtain the polynomial coefficients, computing in each column just the differences of the previous column. For example,
\end{paracol}
\begin{table}[h]
\centering
\bicaption{Tabla de diferencias para el polinomio de Newton-Gregory de cuatro datos}{Table of differences for a Newton-Gregory polynomial of four data}
\begin{tabular}{ccccc}
$x_i$&$y_i$&$\Delta y_i$&$\Delta^2 y_i$&$\Delta^3 y_i$\\
\hline
$x_0=0$&$y_0=\ \ 1$&$-2$&$\ \ 5$&$-7$\\
$x_1=1$&$y_1=-1$&$ \ \ 3$&$ -2$\\
$x_2=2$&$y_2=\ \ 2$&$\ \ 1$\\
$x_3=3$&$y_3=\ \ 3$\\
\end{tabular}
\label{tabnewton}
\end{table}
\begin{paracol}{2}
Una vez calculadas las diferencias, basta dividir por $n!\cdot h^n$ los elementos de la primera fila de la tabla,
\switchcolumn
Once we have computed the differences, it is enough to divide by $n!\cdot h^n$ the elements of the table first row,
\end{paracol}
\begin{equation*}
a_0=1, a_1=\frac{-2}{1}, a_2=\frac{5}{2\cdot 1^2}, a_3=\frac{-7}{6\cdot 1^3}
\end{equation*}
\begin{paracol}{2}
El siguiente código muestra un ejemplo de implementación en Python del polinomio de Newton-Gregory
\switchcolumn
The following code shows an example of Python implementation for the Newton-Gregory polynomial
\end{paracol}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=newton\_gregory.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/newton_gregory.py}
\begin{figure}[h]
\centering
\includegraphics[width=10cm]{intpoli.eps}
\bicaption{Polinomio de interpolación de grado nueve obtenido a partir de un conjunto de diez datos}{Nine degree interpoling polynomial obtained using a set of ten data}
\label{fig:intepol}
\end{figure}
\begin{paracol}{2}
\section{Interpolación por intervalos.}
\sectionmark{Interp. por intervalos \textreferencemark\ Piecewise interpolation}
Hasta ahora, hemos visto cómo interpolar un conjunto de $n+1$ datos mediante un polinomio de grado $n$. En muchos casos, especialmente cuando el número de datos es suficientemente alto, los resultados de dicha interpolación pueden no ser satisfactorios. La razón es que el grado del polinomio de interpolación crece linealmente con el número de puntos a interpolar, así por ejemplo para interpolar 11 datos necesitamos un polinomio de grado 10. Desde un punto de vista numérico, este tipo de polinomios pueden dar grandes errores debido al redondeo. Por otro lado, y dependiendo de la disposición de los datos para los que se realiza la interpolación, puede resultar que el polinomio obtenido tome una forma demasiado complicada para los valores comprendidos entres los datos interpolados..
La figura \ref{fig:intepol} muestra el polinomio de interpolación de grado nueve para un conjunto de 10 datos. Es fácil darse cuenta, simplemente observando los datos, que no hay ninguna razón que justifique las curvas que traza el polinomio entre los puntos $1$ y $2$ o los puntos $9$ y $10$, por ejemplo.
\switchcolumn
\section{Piecewise interpolation}
\sectionmark{Interp. por intervalos \textreferencemark\ Piecewise interpolation}
So far, we have seen how to interpolate a set of $n+1$ data using a degree $n$ polynomial. In many case, in particular when the number of data is high, the results of such interpolation could be very poor. The problem comes from the linear increasing of the polynomial degree with the number of data. So, if we want to build the interpolation polynomial for a 11 data, we come up with a 10-degree polynomial. From a numerical point of view, this kinda polynomial are prone to cast large errors due to the rounding process. On the other hand, depending on how data used to compute the interpolation are distributed, the polynomial could take a too complicate shape that hardly can be related with the information held in the dataset.
Figure \ref{fig:intepol} shows a interpolating polynomial of degree nine obtained from a set of ten data. It is easy to realise, just for simple inspection, that there in not reason to justify the polynomial curvature between points $1$ and $2$ or between the points $9$ and $10$.
\end{paracol}
\begin{figure}
\centering
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=7cm]{steps.eps}
\bicaption{Interpolación de orden cero}{Zero-order interpolation}\label{fig:stepwise}
\end{subfigure}
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=7cm]{lineal.eps}
\bicaption{Interpolación lineal}{Linear interpolation}\label{fig:lineal}
\end{subfigure}
\bicaption{Interpolaciones de orden cero y lineal para los datos de la figura \ref{fig:intepol} }{Zero-order and linear interpolation for the figure data}
\end{figure}
\begin{paracol}{2}
En muchos casos es preferible no emplear todos los datos disponibles para obtener un único polinomio de interpolación. En su lugar, lo que se hace es dividir el conjunto de datos en varios grupos ---normalmente se agrupan formando intervalos de datos consecutivos--- y obtener varios polinomios de menor grado, de modo que cada uno interpole los datos de un grupo distinto.
El grado de los polinomios empleados deberá estar, en principio, relacionado con los datos contenidos en cada tramo.
\paragraph{interpolación de orden cero} \index{Interpolación de orden cero} si hacemos que cada intervalo contenga un solo dato, obtendríamos polinomios de interpolación de grado cero, $a_{0i}=y_i$. El resultado, es un conjunto de escalones cuya valor varía de un intervalo a otro de acuerdo con el dato representativo contenido en cada tramo. La figura \ref{fig:stepwise} muestra el resultado de la interpolación de orden cero para los mismos diez datos de la figura \ref{fig:intepol}.
\paragraph{interpolación lineal.} \index{Interpolación lineal} En este caso, se dividen los datos en grupos de dos. Cada par de datos consecutivos se interpola calculando la recta que pasa por ellos. La interpolación lineal se emplea en muchas aplicaciones debido a su sencillez de cálculo. La figura \ref{fig:lineal}, muestra el resultado de aproximar linealmente los mismos datos contenidos en los ejemplos anteriores.
Siguiendo el mismo procedimiento, aumentando el número de datos contenidos en cada intervalo, podríamos definir una interpolación cuadrática, con polinomios de segundo grado, tomando intervalos que contengan tres puntos, una interpolación cúbica, para intervalos de cuatro puntos etc.
\subsection{Interpolación mediante splines cúbicos} \index{Interpolación!Splines}\index{Splines}
Hemos descrito antes cómo el polinomio interpolador de orden $n$ para un conjunto de $n+1$ datos puede presentar el inconveniente de complicar excesivamente la forma de la curva obtenida entre los puntos interpolados. La interpolación a tramos que acabamos de describir, simplifica la forma de la curva entre los puntos pero presenta el problemas de la continuidad en las uniones entre tramos sucesivos. Sería deseable encontrar métodos de interpolación que fueran capaces de solucionar ambos problemas simultáneamente. Una buena aproximación a dicha solución la proporcionan los \emph{splines}.
Una función \emph{spline} está formada por un conjunto de polinomios, cada uno definido en un intervalo, que se unen entre sí obedeciendo a ciertas condiciones de continuidad.
Supongamos que tenemos una tabla de datos cualquiera,
\switchcolumn
For these reasons, in many cases it is better not to use the whole dataset to build a single interpolation polynomial of maximum degree. Instead, a common practice is to divide the dataset in several groups of data ---usually they are gathered using interval of consecutive data-- and build several polynomial of lower degree, each one interpolating the data of a different group.
The degree of the polynomials should be related with the number of data allocated in each interval.
\paragraph{Zero-order interpolation.} \index[eng]{zero-order interpolation} If we get interval which only hold a single data pair $X,y$, then we get zero-order interpolating polynomials, $a_{0i} = y_i$. The result is a stepwise interpolation which values changes from one interval to the next, taken the data value defined for each interval according to the dataset. Figure \ref{fig:stepwise} shows the zero-order interpolation result for the same ten data of figure \ref{fig:intepol}.
\paragraph{Linear interpolation.} \index[eng]{Linear interpolation} In this case, we divide the dataset in groups of two data. Each two consecutive data are interpolated calculating the line that pass through them. The linear interpolation is very commonly used due to its computing simplicity. Figure \ref{fig:lineal} shows the result of interpolating the same data utilised in previous examples, using linear interpolation.
Following the same procedure, we can increase the number of data include in each interval and define quadratic interpolation, using second-degree polynomials and taking three points in each interval; cubic interpolation,using third-degree polynomial and four point intervals. etc.
\subsection{Cubic spline interpolation}\index[eng]{Interpolation!Splines}\index[eng]{Splines}
WE have seen how the $n$-degree interpolating polynomial for a set of $n+1$ data, could present a quite complex shape that does not represent well the information supplied by the dataset. The piecewise interpolation that we have described so far, simplifies the shape of the interpolating curve but have in turn the problem that it loses the continuity in the union between consecutive intervals. It could be valuable to find interpolation methods that may be able to cope with both problems simultaneously. A good approach to solve these problem is supplied by \emph{spline} interpolation.
A \emph{spline} is function built using a set of polynomials, any one of them defined in an interval. The spline polynomial are connected in the ends of the intervals meeting certain continuity conditions.
Suposse we have a data table whatsoever,
\end{paracol}
\begin{table}[h]
\centering
\begin{tabular}{c|cccc}
x&$x_0$&$x_1$&$\cdots$&$x_n$\\
\hline
y&$y_0$&$y_1$&$\cdots$&$y_n$
\end{tabular}
\end{table}
\begin{paracol}{2}
Para construir una función \emph{spline} $S$ de orden $m$, que interpole los datos de la tabla, se definen intervalos tomando como extremos dos puntos consecutivos de la tabla y un polinomio de grado $m$ para cada uno de los intervalos,
\switchcolumn
To build a $m$ order \emph{spline} function $S$ for interpolating the table data, we define intervals taking two consecutive point onn the table as limits. Then, we define an $m$ degree polynomial for each interval.
\end{paracol}
\begin{equation*}
S= \left\{
\begin{aligned}
S_0(x),& \ x\in [x_0,x_1]\\
S_1(x),& \ x\in [x_1,x_2]\\
\vdots \\
S_i(x),& \ x\in [x_i,x_{i+1}]\\
\vdots \\
S_{n-1}(x),& \ x\in [x_{n-1},x_n]
\end{aligned}
\right.
\end{equation*}
\begin{paracol}{2}
Para que $S$ sea una función Spline de orden $m$ debe cumplir que sea continua y tenga $m-1$ derivadas continuas en el intervalo $[x_0,x_n]$ en que se desean interpolar los datos.
Para asegurar la continuidad, los polinomios que forman $S$ deben cumplir las siguientes condiciones en sus extremos;
\switchcolumn
For $s$ to be a order $m$ spline function it should be continue and it should have $m-1$ continue derivatives in the interval $[x_0,x_n]$ in which we want to interpolate the data.
To ensure the continuity of the polynomials that build $S$ they must satisfy the following condition at their ends,
\end{paracol}
\begin{align*}
S_i(x_{i+1})&=S_{i+1}(x_{i+1}),\ (1\leq i \leq n-1)\\
S'_i(x_{i+1})&=S'_{i+1}(x_{i+1}),\ (1\leq i \leq n-1)\\
S''_i(x_{i+1})&=S''_{i+1}(x_{i+1}),\ (1\leq i \leq n-1)\\
\vdots \\
S^{m-1}_i(x_{i+1})&=S^{m-1}_{i+1}(x_{i+1}),\ (1\leq i \leq n-1)\\
\end{align*}
\begin{paracol}{2}
Es decir, dos polinomios consecutivos del spline y sus $m-1$ primeras derivadas, deben tomar los mismos valores en el extremo común.
Una consecuencia inmediata de las condiciones de continuidad exigidas a los splines es que sus derivadas sucesivas, $S',\ S'', \cdots$ son a su vez funciones spline de orden $m-1,\ m-2, \cdots$. Por otro lado, las condiciones de continuidad suministran $(n-1)\cdot m$ ecuaciones que, unidas a las $n+1$ condiciones de interpolación ---cada polinomio debe pasar por los datos que constituyen los extremos de su intervalo de definición---, suministran un total de $n\cdot (m+1)-(m-1)$ ecuaciones. Este número es insuficiente para determinar los $(m+1)\cdot n$ parámetros correspondientes a los $n$ polinomios de grado $m$ empleados en la interpolación. Las $m-1$ ecuaciones que faltan se obtienen imponiendo a los splines condiciones adicionales.
\paragraph{Splines cúbicos.} \index{Splines! Cubicos} Los splines más empleados son los formados por polinomios de tercer grado. En total, tendremos que determinar $(m+1)\cdot n=4\cdot n$ coeficientes para obtener todos los polinomios que componen el spline. Las condiciones de continuidad más la de interpolación suministran en total $3\cdot (n-1)+n+1=4\cdot n-2$ ecuaciones. Necesitamos imponer al spline dos condiciones más. Algunas típicas son,
\begin{enumerate}
\item Splines naturales $S''(x_0)=S''(x_n)=0$
\item Splines con valor conocido en la primera derivada de los extremos $S'(x_0)=y'_0, S'(x_n)=y'_n$
\item Splines periódicos,
\end{enumerate}
\switchcolumn
That is, two consecutive polynomial belonging to the spline and their $m-1$ first derivatives must take the same values in the common end.
A straightforward consequence of the continuity conditions impose to spline functions is that their successive derivatives $S'.\ S'', \cdots$ are in turn order $m-1, \ m-2 \cdots$ spline functions too. Besides, the continuity conditions supply $(n-1) \cdot m$ equations that, together with the interpolation conditions ---each polynomial should pass through the two data point that defines the ends of its definition interval---, sum up $n\cdot (m+1)-(m-1)$ equations. This number is insufficient for obtaining the $(m+1\cdot n)$ parameters belonging to the the $n$ polynomial of degree $m$ used in the spline interpolation. We need $m-1$ equations more that are defined imposing to the polynomials additional conditions.
\paragraph{Cubic Spline.} Probably, the most used splines are those composed of third-degree polynomials. We must need to determine $(m+1)\dot n = 4\cdot n$ coefficients to obtain all the polynomials that compose the spline. The continuity plus the interpolation conditions supply $3\cdot (n-1)+n+1 = 4\cdot n - 2$ equations. We need to impose two more conditions to the spline. Some frecuently used conditions are,
\begin{enumerate}
\item natural Spline $S''(x_0)=S''(x_n)=0$
\item Spline with a known value for the derivatives at the ends of the interval $S'(x_0)=y'_0, S'(x_n)=y'_n$
\item Periodic Spline,
\end{enumerate}
\end{paracol}
\begin{equation*}
\left\{
\begin{aligned}
S(x_0)&=S(x_n)\\
S'(x_0)&=S'(x_n)\\
S''(x_0)&=S''(x_n)
\end{aligned}
\right.
\end{equation*}
\begin{paracol}{2}
Intentar construir un sistema de ecuaciones para obtener a la vez todos los coeficientes de todos los polinomios es una tarea excesivamente compleja porque hay demasiados parámetros. Para abordar el problema partimos del hecho de que $S''(x)$ es también un spline de orden 1 para los puntos interpolados. Si los definimos como,
\switchcolumn
Try to build a system of equations to obtain all the coefficients of all the polynomial at a time, is an arduous task. There are too many parameters. We can address the problem starting with $S''(x)$, which it is also a order-1 spline for the points we want to interpolate. If we define it as,
\end{paracol}
\begin{equation*}
S''_i(x)=-M_i\frac{x-x_{i+1}}{h_i}+M_{i+1}\frac{x-x_i}{h_i},\ i=0,\cdots, n-1
\end{equation*}
\begin{paracol}{2}
donde $h_i=x_{i+1}-x_i$ representa el ancho de cada intervalo y donde cada valor $M_i=S''(x_i)$ será una de las incógnitas que deberemos resolver.
Si integramos dos veces la expresión anterior,
\switchcolumn
Where $h_i=x_{i+1}-x_i$ stand for each interval width and where the value $M_i=S''(x_i)$ will be the unknown we have to solve.
Now, we integrate two times this expression, $S_i''(x)$, to obtain,
\end{paracol}
\begin{align*}
S'_i(x)&=-M_i\frac{(x-x_{i+1})^2}{2\cdot h_i}+M_{i+1}\frac{(x-x_i)^2}{2\cdot h_i}+A_i,\ i=0,\cdots, n-1\\
S_i(x)&=-M_i\frac{(x-x_{i+1})^3}{6\cdot h_i}+M_{i+1}\frac{(x-x_i)^3}{6\cdot h_i}+A_i(x-x_i)+B_i,\ i=0,\cdots, n-1\\
\end{align*}
\begin{paracol}{2}
Empezamos por imponer las condiciones de interpolación: el polinomio $S_i$ debe pasar por el punto $(x_i,y_i)$,
\switchcolumn
Let's start imposing the interpolation conditions: the polynomial $S_i$ must to pass through the point $(x_i,y_i)$,
\end{paracol}
\begin{equation*}
S_i(x_i)=-M_i\frac{(x_i-x_{i+1})^3}{6\cdot h_i}+B_i=y_i \Rightarrow B_i=y_i-\frac{M_i\cdot h_i^2}{6},\ i=0,\cdots, n-1
\end{equation*}
\begin{paracol}{2}
A continuación imponemos continuidad del spline en los nodos comunes: El polinomio $S_{i-1}$ también debe pasar por el punto $(x_i, y_i)$,
\switchcolumn
Then, we impose the continuity of the spline in the points common to two polynomials: Polynomial $S_{i-1}$ must also pass through the point $(x_i, y_i)$,
\end{paracol}
\begin{align*}
S_{i-1}(x_i)&=M_i\frac{(x_i-x_{i-1})^3}{6\cdot h_i}+A_{i-1}(x_i-x_{i-1})+\overbrace{y_{i-1}-\frac{M_{i-1}\cdot h_{i-1}^2}{6}}^{B_{i-1}}=y_i \Rightarrow\\
\Rightarrow A_{i-1}&=\frac{y_i-y_{i-1}}{h_{i-1}}-\frac{M_i-M_{i-1}}{6}\cdot h_{i-1}, \ i=1,\cdots, n
\end{align*}
\begin{paracol}{2}
Y por tanto,
\switchcolumn
and thus,
\end{paracol}
\begin{equation*}
A_i=\frac{y_{i+1}-y_i}{h_i}-\frac{M_{i+1}-M_i}{6}\cdot h_i, \ i=0,\cdots, n-1
\end{equation*}
\begin{paracol}{2}
En tercer lugar imponemos la condición de que las derivadas también sean continuas en los nodos comunes,
\switchcolumn
Thirdly, we impose that continuity condition to the derivatives, in the common end of two consecutive polynomials,
\end{paracol}
\begin{align*}
S'_i(x_i)&=-M_i\frac{(x_i-x_{i+1})^2}{2\cdot h_i}+M_{i+1}\frac{(x_i-x_i)^2}{2\cdot h_i}+\frac{y_{i+1}-y_i}{h_i}-\frac{M_{i+1}-M_i}{6}\cdot h_i,\ i=0,\cdots, n-1\\
S'_{i-1}(x_i)&=-M_{i-1}\frac{(x_i-x_i)^2}{2\cdot h_{i-1}}+M_{i}\frac{(x_i-x_{i-1})^2}{2\cdot h_{i-1 }}+\frac{y_i-y_{i-1}}{h_{i-1}}-\frac{M_i-M_{i-1}}{6}\cdot h_{i-1},\ i=1,\cdots, n\\
S'_i(x_i)&=S'_{i-1}(x_i) ,\ i=1,\cdots, n-1 \Rightarrow\\
&\Rightarrow -M_i\frac{h_i}{2}+\frac{y_{i+1}-y_i}{h_i}-\frac{M_{i+1}-M_i}{6}\cdot h_i=M_{i}\frac{h_{i-1}}{2}+\frac{y_i-y_{i-1}}{h_{i-1}}-\frac{M_i-M_{i-1}}{6}\cdot h_{i-1}
\end{align*}
\begin{paracol}{2}
Si agrupamos a un lado los valores $M_{i-1}, M_i, M_{i+1}$,
\switchcolumn
If we group at one side the values $M_{i-1}, M_i, M_{i+1}$,
\end{paracol}
\begin{align*}
h_{i-1}\cdot M_{i-1}+2\cdot (h_{i-1}+h_i)\cdot M_i+h_i\cdot M_{i+1}=6\cdot \left(\frac{y_{i+1}-y_i}{h_i}-\frac{y_i-y_{i-1}}{h_{i-1}}\right)\\
i=1,\cdots ,n-1
\end{align*}
\begin{paracol}{2}
En total tenemos $M_0,\cdots, M_n$, $n+1$ incógnitas y la expresión anterior, solo nos suministra $n-1$ ecuaciones. Necesitamos dos ecuaciones más. Si imponemos la condición de splines naturales, para el extremo de la izquierda del primer polinomio y para el extremo de la derecha del último,
\switchcolumn
We have in total $M_0,\cdots, M_n$, $n+1$ unknowns and the above expression only supply $n-1$ equations. We need two more equations. If we impose the conditions for a natural spline for the left end of the first polynomial and for the right end of the last one,
\end{paracol}
\begin{align*}
M_0=S''(x_0)=0\\
M_n=S''(x_n)=0
\end{align*}
\begin{paracol}{2}
Con estas condiciones y la expresión obtenida para el resto de los $M_i$, podemos construir un sistema de ecuaciones tridiagonal
\switchcolumn
With these last conditions and the expression obtained for the remaining $M_i$, we can build a tridiagonal system of equations
\end{paracol}
\begin{equation*}
\begin{pmatrix}
2(h_0+h_1) & h_1 & 0 &0&\cdots &0&0\\
h_1 & 2(h_1+h_2) & h_2 &0& \cdots&0 & 0\\
0& h_2 & 2(h_2+h_3) & h_3 &\cdots &0& 0\\
\vdots & \vdots & \vdots &\vdots& \ddots & \vdots&\vdots \\
0 & 0 & 0&0&\cdots& 2(h_{n-3}+h_{n-2}) & h_{n-2} \\
0 & 0 & 0&0&\cdots&h_{n-2} & 2(h_{n-2}+h_{n-1})
\end{pmatrix}\cdot \begin{pmatrix}
M_1\\
M_2\\
M_3\\
\vdots \\
M_{n-1}
\end{pmatrix}=\begin{pmatrix}
b_1\\
b_2\\
b_3\\
\vdots \\
b_{n-1}
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
Donde hemos hecho,
\switchcolumn
Where,
\end{paracol}
\begin{equation*}
b_i=6\cdot \left(\frac{y_{i+1}-y_i}{h_i}-\frac{y_i-y_{i-1}}{h_{i-1}}\right)
\end{equation*}
\begin{paracol}{2}
Tenemos un sistema de ecuaciones en el que la matriz de coeficientes es tridiagonal y además diagonal dominante, por lo que podríamos emplear cualquiera de los métodos vistos en el capítulo
\ref{sistemas}. Una vez resuelto el sistema y obtenidos los valores de $M_i$, obtenemos los valores de $A_i$ y $B_i$ a Partir de las ecuaciones obtenidas más arriba.
Por último, la forma habitual de definir el polinomio de grado 3 $S_i$, empleado para interpolar los valores del intervalo $[x_i,x_{i+1}]$, mediante splines cúbicos se define como,
\switchcolumn
So, we have a system of equations for which the coefficients matrix is tridiagonal and, besides, it is a dominant diagonal matrix. For this reason, we can solve it with anyone of the methods described in chapter \ref{sistemas}. Once the system is solved, we get the values of $M_i$ and the values of $A_i$ and $B_i$ using the equations described above.
A last remark: we usually define the 3-degree polynomial, $S_i$ used for interpolating the values inside the interval $[x_i,x_{i+1}]$ as follows,
\end{paracol}
\begin{equation*}
S_i(x)=\alpha_i+\beta_i(x-x_i)+\gamma_i(x-x_i)^2+\delta_i(x-x_i)^3, \ x\in [x_i,x_{i+1}],\ (i=0,1,\cdots,n-1)
\end{equation*}
\begin{paracol}{2}
Donde,
\switchcolumn
Where,
\end{paracol}
\begin{align*}
\alpha_i &=y_i\\
\beta_i &=\frac{y_{i+1}-y_i}{h_i}-\frac{M_i \cdot h_i}{3}-\frac{M_{i+1} \cdot h_i}{6}\\
\gamma_i &=\frac{M_i}{2}\\
\delta_i &=\frac{M_{i+1}-M_i}{6\cdot h_i}
\end{align*}
\begin{paracol}{2}
La siguiente función permite obtener los coeficientes y el resultado de interpolar un conjunto de puntos mediante splines cúbicos,
\switchcolumn
The following Python code computes the coefficients of the cubic spline defined using a dataset and the value taken by the spline at any point.
\end{paracol}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=cubic\_spline.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/cubic_spline.py}
\begin{paracol}{2}
La figura, \ref{fig:splines} muestra el resultado de interpolar mediante un spline cúbico, los datos contenidos en la figura \ref{fig:intepol}. Es fácil observar cómo ahora los polinomios de interpolación dan como resultado una curva suave en los datos interpolados y en la que además las curvas son también suaves, sin presentar variaciones extrañas, para los puntos contenidos en cada intervalo entre dos datos.
\subsection{Funciones propias de Py\-thon para interpolación por intervalos} \index{interp1@\texttt{interp1}}
Para realizar una interpolación por intervalos mediante cualquiera de los procedimientos descritos, podemos emplear el subpaquete de scipy \mintinline{python}{Scipy.interpolate}. Este paquete incorpora múltiples métodos de interpolación; solo veremos dos:
La función \texttt{interp1d}. Esta función admite como variables de entrada dos arrays con los valores de las coordenadas $x$ e $y$ de los datos que se desea interpolar. Además, admite como variable de entrada una cadena de caracteres que indica el método con el que se quiere realizar la interpolación. Dicha variable puede tomar los valores:
\begin{enumerate}
\item \texttt{'nearest'}. Interpola el intervalo empleando el valor $y_i$ correspondiente al valor $x_i$ más cercano al punto que se quiere interpolar. El resultado es una interpolación a escalones.
del conjunto de datos que se desea interpolar.
\item \texttt{'next'}. Interpola el interpalo empleando el valor de $y_i$ correspondiente al punto $x_i$ de los datos que cierra el intervalo.
\item \texttt{'previous'} Interpola el interpalo empleando el valor de $y_i$ correspondiente al punto $x_i$ de los datos que abre el intervalo.
\item \texttt{'linear'} realiza una interpolación lineal entre los extremos del intervalo que se desea intepolar. Esta es la opción por defecto.
\end{enumerate}
\mintinline{python}{interp1d} Devuelve una funcion que admite como variable de entrada un array con los puntos para para los que se quiere calcular el valor de la interpolación y devuelve como salidad un array con los resultados obtenidos. El siguiente código muestra el modo de usar el comando \texttt{interp1d}. Para probarlo se han creado dos array \texttt{x} e \texttt{y} que contienen el conjunto de datos que se empleará para calcular la interpolación. Además, se ha creado otro vector \texttt{xi} que contiene los puntos para los que se quiere calcular el resultado de la interpolación.
\switchcolumn
Figure \ref{fig:splines} shows the result of interpolating the same data of figure \ref{fig:intepol} using a cubic spline. It is ease to check how the interpolation polynomials which compose the spline cast a smooth result in the points interpolated and how the curves shapes are reasonable smooth also in the intervals between the data. They do not present variations difficult to explain using the data.
\subsection{Python functions for piecewise interpolation}
To carry out a piecewise interpolation using anyone of the method above described, we can use the \mintinline{python}{scipy } sub-package \mintinline{python}{scypi.interpolate}. This package includes many intepolation me\-thods; we will only describe two of them:
The \mintinline{python}{interp1d} function. This function takes two arrays as inpunt variables with the ccordenates $x$ and $y$ values belonging to the data we want to interpolate. In addition, the function may take also a character string, as an input variable which defines the method we want to use to carry out the interpolation. This last variable can take the following values:
\begin{enumerate}
\item \texttt{'nearest'}. It interpolates the interval using the value $y_i$ corresponding to the value $x_i$ nearest to the point at which we want to compute the interpolation. The result is stepwise interpolation.
\item \texttt{'next'}. It interpolates the interval using the value $y_i$ corresponding to the value $x_i$ which closes the interval in which we want to compute the interpolation.
\item \texttt{'previous'} It interpolates the interval using the value $y_i$ corresponding to the value $x_i$ which opens the interval in which we want to compute the interpolation.
\item \texttt{'linear'} It calculates a linear interpolation between the points at the ends of the interval we want to interpolate. This is the default option.
\end{enumerate}
\mintinline{python}{interp1d} returns a function that, in turn, takes as input variable an array with the points we want to calculate the interpolation at, and returns an array we the computed results. The following code shows how to use the function \mintinline{python}{interp1d}. To try it we have created two arrays \mintinline{python}{x} and \mintinline{python}{y} which contain the dataset we want to interpolate. Besidas, we have created another array \mintinline{python}{xi} with the point we want to compute the interpolation at.
\end{paracol}
\begin{figure}
\centering
\includegraphics[width=12cm]{splines.eps}
\bicaption{Interpolación mediante spline cúbico de los datos de la figura}{Cubic Spline interpolation for the data represented in the figure} \ref{fig:intepol}
\label{fig:splines}
\end{figure}
\inputminted[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
%bgcolor=LightGray,
label=ejemplo\_interp1d.py,
fontsize=\footnotesize,
linenos
]{python}{./codigos/interpolacion/ejemplo_interp1d.py}
\begin{paracol}{2}
La segunda función interpoladora de\\ \mintinline{python}{scipy.interpolation} que vamos a describir se llama \mintinline{python}{CubicSpline}. Permite interpolar empleando Splines cúbicos. En este caso, además de los datos $x$ e $y$ necesarios para definir el spline, la función admite el parametro \mintinline{python}{bc_type}, que permite determinar las condiciones de contorno en los extremos del spline. Las opciones posibles son:
\mintinline{python}{bc_type='not__knot'}. Es la opcion por defecto. Hace que el polinomio empleado en el primer y segundo segmento en los extremos del spline sea el mismo.
\mintinline{python}{bc_type='natural'}. Spline natural.
\mintinline{python}{bc_type='periodic'}. Spline periódico.
Hay más opciones; los interesados pueden encontrarlas en la documentación de \mintinline{python}{scipy}. El uso es similar al descrito para \mintinline{python}{interp1d}. A partir de los datos se crea una función interpoladora que permite calcular el valor de la imagen en los puntos que se desee. Por ejemplo, para splines naturales sería,
\switchcolumn
The second interpolating function, from\\ \mintinline{python}{scipy.interpolation} we are going to describe is \mintinline{python}{CubicSpline}. This function, as can be expected, uses cubic splines to perform the interpolation of a dataset. In this cases, in addition to the $x$ and $y$ data needed to define the spline, the function defines an input paramenter \mintinline{python}{bc_type}, which allows us to stablish the boundary conditions in the ends of the spline. Some of the available options are:
\mintinline{python}{bc_type='not__knot'}. This is the default option. The first and second segments at an end of the spline uses the same polynomial.
\mintinline{python}{bc_type='natural'}. Natural spline.
\mintinline{python}{bc_type='periodic'}. Periodic spline.
There are more options. Those interested can find them in \mintinline{python}{scipy} documentation. Its use is similar to the use of \mintinline{python}{interp1d}. From the data we want to interpolate \mintinline{python}{CubiSpline} generates an interpoling function which alows us to compute the spline value in the point we wish. For instance, for natural splines we write,
\end{paracol}
\begin{center}
\begin{minipage}{.5\textwidth}
\begin{minted}{python}
spnat = CubicSpline(x,y,'natural')
yi = spnat(xi)
\end{minted}
\end{minipage}
\end{center}
\begin{paracol}{2}
\section{Ajuste polinómico por el método de mínimos cuadrados}\label{sec:mc}\index{Mínimos cuadrados} \index{Ajuste polinómico}
\sectionmark{Mínimos cuadrados \textreferencemark\ Least squares}