-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsistemas.tex
3611 lines (2827 loc) · 152 KB
/
sistemas.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{Sistemas de ecuaciones lineales\\ Linear equation systems}\index{sistemas} \index[eng]{systems}
\chaptermark{Sistemas \textreferencemark\ Systems}
\epigraph{Después de cada guerra \\ alguien tiene que limpiar. \\ No se van a ordenar solas las cosas, \\ digo yo. (Maria Wisława Anna Szymborska)}
\begin{paracol}{2}
\section{Introducción}
Una ecuación lineal es aquella que establece una relación \emph{lineal} entre dos o más variables, por ejemplo,
\begin{equation*}
3x_1-2x_2=12
\end{equation*}
Se dice que es una relación lineal, porque las variables están relacionadas entre sí tan solo mediante sumas y productos por coeficientes constantes. En particular, el ejemplo anterior puede representarse geométricamente mediante una línea recta.
El número de variables relacionadas en una ecuación lineal determina la dimensión de la ecuación. La del ejemplo anterior es una ecuación bidimensional, puesto que hay dos variables. El número puede ser arbitrariamente grande en general,
\begin{equation*}
a_1x_1+a_2x_2+\cdots +a_nx_n=b
\end{equation*}
será una ecuación n-dimensional.
\switchcolumn
\section{Introduction}
A linear equation is an equation that establishes a \emph{linear} relationship between two or more variables, for example,
\begin{equation}
3x_1-2x_2=12
\end{equation}
It is said to be a linear relationship, because the variables are related to each other only through additions and products by constant coefficients. In particular, the above example can be represented geometrically by a straight line.
The number of related variables in a linear equation determines the dimension of the equation. The above example is a two-dimensional equation, since there are two variables. The number can be arbitrarily large in general,
\begin{equation*}
a_1x_1+a_2x_2+cdots +a_nx_n=b
\end{equation*}
will be an n-dimensional equation.
\switchcolumn
Como ya hemos señalado más arriba, una ecuación bidimensional admite una línea recta como representación geométrica, una ecuación tridimensional admitirá un plano y para dimensiones mayores que tres cada ecuación representará un hiperplano de dimension n. Por supuesto, para dimensiones mayores que tres, no es posible obtener una representación gráfica de la ecuación.
Las ecuaciones lineales juegan un papel muy importante en la física y, en general en la ciencia y la tecnología. La razón es que constituyen la aproximación matemática más sencilla a la relación entre magnitudes físicas. Por ejemplo cuando decimos que la fuerza aplicada a un resorte y la elongación que sufre están relacionadas por la ley de Hooke, $F=Kx$ estamos estableciendo una relación lineal entre las magnitudes fuerza y elongación. ¿Se cumple siempre dicha relación? Desde luego que no. Pero es razonablemente cierta para elongaciones pequeñas y, apoyados en ese sencillo modelo \emph{lineal} de la realidad, se puede aprender mucha física.
Un sistema de ecuaciones lineales está constituido por varias ecuaciones lineales, que expresan relaciones lineales distintas sobre las mismas variables. Por ejemplo,
\begin{align*}
a_{11}x_1+a_{12}x_2&=b_1\\
a_{21}x_1+a_{22}x_2&=b_2
\end{align*}
\switchcolumn
As we have already pointed out above, a two-dimensional equation admits a straight line as geometrical representation, a three-\-di\-men\-sio\-nal equation will admit a plane and for dimensions greater than three each equation will represent a hyperplane of dimension n. Of course, for dimensions greater than three, it is not possible to obtain a graphical representation of the equation.
Linear equations play a very important role in physics and, in general, in science and technology. The reason is that they are the simplest mathematical approximation of the relationship between physical quantities. For example, when we say that the force applied to a spring and the elongation it undergoes are related by Hooke's law, $F=Kx$, we are establishing a linear relationship between the quantities force and elongation. Does this relationship always hold true? Certainly not. But it is reasonably true for small elongations and, based on this simple \emph{linear} model of reality, a lot of physics can be learned.
A system of linear equations is made up of several linear equations, which express different linear relationships about the same variables. For example,
\begin{align*}
a_{11}x_1+a_{12}x_2&=b_1\\
a_{21}x_1+a_{22}x_2&=b_2
\end{align*}
\switchcolumn
Se llaman soluciones del sistema de ecuaciones a los valores de las variables que satisfacen simultáneamente a todas las ecuaciones que componen el sistema. Desde el punto de vista de la obtención de las soluciones a las variables se les suele denominar incógnitas, es decir valores no conocidos que deseamos obtener o calcular.
Un sistema de ecuaciones puede tener infinitas soluciones, puede tener una única solución o puede no tener solución. En lo que sigue, nos centraremos en sistemas de ecuaciones que tienen una única solución.
Una primera condición para que un sistema de ecuaciones tengan una única solución es que el número de incógnitas presentes en el sistema coincida con el número de ecuaciones.
\switchcolumn
The values of the variables that simultaneously satisfy all the equations that make up the system are called solutions of the system of equations. From the point of view of obtaining the solutions, the variables are usually called unknowns, i.e. unknown values that we wish to obtain or calculate.
A system of equations can have infinite solutions, it can have only one solution or it can have no solution. In what follows, we will focus on systems of equations that have only one solution.
A first condition for a system of equations to have a unique solution is that the number of unknowns present in the system coincides with the number of equations.
\switchcolumn
De modo general podemos decir que vamos a estudiar métodos numéricos para resolver con un computador sistemas de $n$ ecuaciones con $n$ incógnitas,
\begin{align*}
a_{11}&x_1+a_{12}x_2+\cdots +a_{1n}x_n=b_1\\
a_{21}&x_1+a_{22}x_2+\cdots +a_{2n}x_n=b_2\\
\cdots & \\
a_{n1}&x_1+a_{n2}x_2+\cdots +a_{nn}x_n=b_n
\end{align*}
Una de las grandes ventajas de los sistemas de ecuaciones lineales es que puede expresarse en forma de producto matricial,
\switchcolumn
In general terms, we can say that we are going to study numerical methods to solve with a computer systems of $n$ equations with $n$ unknowns,
\begin{align*}
a_{11}&x_1+a_{12}x_2+\cdots +a_{1n}x_n=b_1\\
a_{21}&x_1+a_{22}x_2+\cdots +a_{2n}x_n=b_2\\
\cdots & \\
a_{n1}&x_1+a_{n2}x_2+\cdots +a_{nn}x_n=b_n
\end{align*}
One of the great advantages of systems of linear equations is that they can be expressed in matrix product form,
\end{paracol}
\begin{equation*}
\left. \begin{aligned}
a_{11}&x_1+a_{12}x_2+\cdots +a_{1n}x_n=b_1\\
a_{21}&x_1+a_{22}x_2+\cdots +a_{2n}x_n=b_2\\
\cdots & \\
a_{n1}&x_1+a_{n2}x_2+\cdots +a_{nn}x_n=b_n
\end{aligned}\right\} \Rightarrow \overbrace{\begin{pmatrix}
a_{11}& a_{12}& \cdots & a_{1n}\\
a_{21}& a_{22}& \cdots & a_{2n}\\
\vdots & \vdots & \ddots & \vdots\\
a_{n1}& a_{n2}& \cdots & a_{nn}
\end{pmatrix}}^A \cdot \overbrace{\begin{pmatrix}
x_1\\
x_2\\
\vdots \\
x_n
\end{pmatrix}}^x=\overbrace{\begin{pmatrix}
b_1\\
b_2\\
\vdots \\
b_n
\end{pmatrix}}^b
\end{equation*}
\begin{paracol}{2}
La matriz $A$ recibe el nombre de matriz de coeficientes del sistema de ecuaciones, el vector $x$ es el vector de incógnitas y el vector $b$ es el vector de términos independientes. Para resolver un sistema de ecuaciones podríamos aplicar álgebra de matrices, como se ha visto en el capítulo \ref{ch:numpy}:
\switchcolumn
The matrix $A$ is called the coefficient matrix of the system of equations, the vector $x$ is the vector of unknowns and the vector $b$ is the vector of independent terms. To solve a system of equations we could apply matrix algebra, as discussed in chapter \ref{ch:numpy}:
\end{paracol}
\begin{equation*}
A\cdot x=b \Rightarrow x=A^{-1}\cdot b
\end{equation*}
\begin{paracol}{2}
Es decir, bastaría invertir la matriz de coeficientes y multiplicarla por la izquierda por el vector de coeficientes para obtener el vector de términos independientes. De aquí podemos deducir una segunda condición para que un sistema de ecuaciones tenga una solución única. Su matriz de coeficientes tiene que tener inversa. Veamos algunos ejemplos sencillos.
Tomaremos en primer lugar un sistema de dos ecuaciones con dos incógnitas,
\begin{align*}
4x_1+x_2&=6\\
3x_1-2x_2&=-1
\end{align*}
Si expresamos el sistema en forma de producto de matrices obtenemos,
\switchcolumn
That is, it would be enough to invert the matrix of coefficients and multiply it on the left by the vector of coefficients to obtain the vector of independent terms. From this we can deduce a second condition for a system of equations to have a unique solution; its coefficient matrix must have an inverse. Let us look at some simple examples.
We will first take a system of two equations with two unknowns,
\begin{align*}
4x_1+x_2&=6 \\
3x_1-2x_2&=-1
\end{align*}
If we express the system as a product of matrices we obtain,
\end{paracol}
\begin{equation*}
\begin{pmatrix}
4& 1\\
3& -2
\end{pmatrix} \cdot \begin{pmatrix}
x_1\\
x_2
\end{pmatrix}=\begin{pmatrix}
6\\
-1
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
e invirtiendo la matriz de coeficientes y multiplicándola por el vector de términos independientes se llega al vector de soluciones del sistema,
\switchcolumn
and by inverting the coefficient matrix and multiplying it by the vector of independent terms we arrive at the vector of solutions of the system,
\end{paracol}
\begin{equation*}
\begin{pmatrix}
x_1\\
x_2
\end{pmatrix}= \begin{pmatrix}
4& 1\\
3& -2
\end{pmatrix}^{-1} \cdot \begin{pmatrix}
6\\
-1
\end{pmatrix}=\begin{pmatrix}
2/11& 1/11\\
3/11& -4/11
\end{pmatrix}\begin{pmatrix}
6\\
-1
\end{pmatrix}=\begin{pmatrix}
1\\
2
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
En el ejemplo que acabamos de ver, cada ecuación corresponde a una recta en el plano, en la figura \ref{fig:recta1} se han representado dichas rectas gráficamente. El punto en que se cortan es precisamente la solución del sistema.
\switchcolumn
In the example we have just seen, each equation corresponds to a line in the plane, in the figure \ref{fig:recta1} these lines have been represented graphically. The point where they intersect is precisely the solution of the system.
\end{paracol}
\begin{figure}[h]
\centering
\includegraphics[width=12cm]{recta1}
\bicaption{Sistema de ecuaciones con solución única}{Equation system with unique solution}
\label{fig:recta1}
\end{figure}
\begin{paracol}{2}
Supongamos ahora el siguiente sistema, también de dos ecuaciones con dos incógnitas,
\begin{align*}
4x_1+x_2&=6\\
2x_1+\frac{1}{2} x_2&=-1
\end{align*}
El sistema no tiene solución. Su matriz de coeficientes tiene determinante cero, por lo que no es invertible,
\begin{equation*}
\vert A \vert =\begin{vmatrix}
4& 1\\
2& 1/2
\end{vmatrix} =0 \Rightarrow \nexists A^{-1}
\end{equation*}
\switchcolumn
Now suppose the following system, also of two equations with two unknowns,
\begin{align*}
4x_1+x_2&=6\\
2x_1+\frac{1}{2} x_2&=-1
\end{align*}
The system has no solution. Its coefficient matrix has zero determinant, so it is not invertible,
\begin{equation*}
\vert A \vert =\begin{vmatrix}
4& 1\\
2& 1/2
\end{vmatrix} =0 \Rightarrow \nexists A^{-1}
\end{equation*}
\switchcolumn
Si representamos gráficamente las dos ecuaciones de este sistema (figura \ref{fig:recta2}) es fácil entender lo que pasa, las rectas son paralelas, no existe ningún punto $(x_1,x_2)$ que pertenezca a las dos rectas, y por tanto el sistema carece de solución.
\switchcolumn
If we represent graphically the two equations of this system (figure \ref{fig:recta2}) it is easy to understand what happens, the lines are parallel, there is no point $(x_1,x_2)$ that belongs to the two lines, and therefore the system has no solution.
\end{paracol}
\begin{figure}[h]
\centering
\includegraphics[width=12cm]{recta2}
\bicaption{Sistema de ecuaciones sin solución}{Equation system without solution}
\label{fig:recta2}
\end{figure}
\begin{paracol}{2}
Dos rectas paralelas lo son, porque tienen la misma pendiente. Esto se refleja en la matriz de coeficientes, en que las filas son proporcionales; si multiplicamos la segunda fila por dos, obtenemos la primera.
\switchcolumn
Two parallel lines are parallel because they have the same slope. This is reflected in the coefficient matrix, where the rows are proportional; if we multiply the second row by two, we get the first row.
\switchcolumn
Por último, el sistema,
\begin{align*}
4x_1+x_2&=6\\
2x_1+\frac{1}{2} x_2&=3
\end{align*}
posee infinitas soluciones. La razón es que la segunda ecuación es igual que la primera multiplicada por dos: es decir, representa exactamente la misma relación lineal entre las variables $x_1$ y $x_2$, por tanto, todos los puntos de la recta son solución del sistema. De nuevo, la matriz de coeficientes del sistema no tiene inversa ya que su determinante es cero.
\switchcolumn
Finally, the system,
\begin{align*}
4x_1+x_2&=6 \\
2x_1+\frac{1}{2} x_2&=3
\end{align*}
has infinite solutions. The reason is that the second equation is the same as the first equation multiplied by two: that is, it represents exactly the same linear relationship between the variables $x_1$ and $x_2$, therefore, all the points on the line are solutions of the system. Again, the coefficient matrix of the system has no inverse since its determinant is zero.
\end{paracol}
\begin{figure}[h]
\centering
\includegraphics[width=12cm]{recta3.eps}
\bicaption{Sistema de ecuaciones con infinitas soluciones}{Equation system with infinite solutions}
\label{recta3}
\end{figure}
\begin{paracol}{2}
Para sistemas de ecuaciones de dimensión mayor, se cumple también que que el sistema no tiene solución única si el determinante de su matriz de coeficiente es cero. En todos los demás casos, es posible obtener la solución del sistema invirtiendo la matriz de coeficientes y multiplicando el resultado por el vector de términos independientes.
En cuanto un sistema de ecuaciones tiene una dimensión suficientemente grande, invertir su matriz de coeficientes se torna un problema costoso o sencillamente inabordable.
Desde un punto de vista numérico, la inversión de una matriz, presenta frecuentemente problemas debido al error de redondeo en las operaciones. Por esto, casi nunca se resuelven los sistemas de ecuaciones invirtiendo su matriz de coeficientes. A lo largo de este capítulo estudiaremos dos tipos de métodos de resolución de sistemas de ecuaciones. El primero de ellos recibe el nombre genérico de métodos directos, el segundo tipo lo constituyen los llamados métodos iterativos.
\switchcolumn
For higher dimensional systems of equations, it is also true that the system has no unique solution if the determinant of its coefficient matrix is zero. In all other cases, it is possible to obtain the solution of the system by inverting the coefficient matrix and multiplying the result by the vector of independent terms.
As soon as a system of equations has a sufficiently large dimension, inverting its coefficient matrix becomes a costly or simply intractable problem.
From a numerical point of view, the inversion of a matrix often presents problems due to the rounding error in the operations. For this reason, systems of equations are almost never solved by inverting their matrix of coefficients. Throughout this chapter we will study two types of methods for solving systems of equations. The first of these is known generically as direct methods, while the second type is known as iterative methods.
\end{paracol}
\begin{paracol}{2}
\section{Condicionamiento}
En la introducción hemos visto que para que un sistema de ecuaciones tenga solución, es preciso que su matriz de coeficientes sea invertible. Sin embargo cuando tratamos de resolver un sistema de ecuaciones numéricamente, empleando un ordenador, debemos antes examinar cuidadosamente la matriz de coeficientes del sistema. Veamos un ejemplo: el sistema,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4 x_2&=-1
\end{align*}
\switchcolumn
\section{Condition number}
In the introduction we have seen that for a system of equations to have a solution, its coefficient matrix must be invertible. However, when we try to solve a system of equations numerically, using a computer, we must first carefully examine the matrix of coefficients of the system. Let us look at an example: the system,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4 x_2&=-1
\end{align*}
\switchcolumn
Tiene como soluciones,
\begin{equation*}
x=\begin{pmatrix}
-8.5\\
40
\end{pmatrix}
\end{equation*}
\switchcolumn
Has the following solutions,
\begin{equation*}
x=\begin{pmatrix}
-8.5\\
40
\end{pmatrix}
\end{equation*}
\switchcolumn
Si alteramos ligeramente uno de sus coeficientes,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4{\color{red}9} x_2&=-1
\end{align*}
\switchcolumn
If we slightly change one of the coefficients,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4{\color{red}9} x_2&=-1
\end{align*}
\switchcolumn
Las soluciones se alteran bastante; se vuelven aproximadamente 10 veces más grande,
\begin{equation*}
x=\begin{pmatrix}
-98.5\\
400
\end{pmatrix}
\end{equation*}
\switchcolumn
The solutions become quite altered; they become about 10 times larger,
\begin{equation*}
x=\begin{pmatrix}
-98.5\\
400
\end{pmatrix}
\end{equation*}
\switchcolumn
y si volvemos a alterar el mismo coeficiente,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4{\color{red}99} x_2&=-1
\end{align*}
\switchcolumn
if we change again the same coefficient,
\begin{align*}
4x_1+x_2&=6\\
2x_1+0.4{\color{red}99} x_2&=-1
\end{align*}
\switchcolumn
La solución es aproximadamente 100 veces más grande,
\begin{equation*}
x=\begin{pmatrix}
-998.5\\
4000
\end{pmatrix}
\end{equation*}
\switchcolumn
The solution is about 100 times larger,
\begin{equation*}
x=\begin{pmatrix}
-998.5\\
4000
\end{pmatrix}
\end{equation*}
\switchcolumn
La razón para estos cambios es fácil de comprender intuitivamente; a medida que aproximamos el coeficiente a $0.5$, estamos haciendo que las dos ecuaciones lineales sean cada vez mas paralelas, pequeñas variaciones en la pendiente, modifican mucho la posición del punto de corte.
Cuando pequeñas variaciones en la matriz de coeficientes generan grandes variaciones en las soluciones del sistema, se dice que el sistema está mal condicionado, en otras palabras: que no es un sistema bueno para ser resuelto numéricamente. Las soluciones obtenidas para un sistema mal condicionado, hay que tomarlas siempre con bastante escepticismo.
Para estimar el buen o mal condicionamiento de un sistema, se emplea el número de condición, que definimos en el capítulo \ref{ch:numpy} en la sección \ref{sec:SVD}, al hablar de la factorización SVD. El número de condición de una matriz es el cociente entre sus valores singulares mayor y menor. Cuanto más próximo a $1$ sea el número de condición, mejor condicionada estará la matriz y cuanto mayor sea el número de condición peor condicionada estará.
\switchcolumn
The reason for these changes is easy to understand intuitively; as we bring the coefficient closer to $0.5$, we are making the two linear equations more and more parallel, and small variations in the slope greatly modify the position of the cut-off point.
When small variations in the matrix of coefficients generate large variations in the solutions of the system, it is said that the system is ill-conditioned, in other words: that it is not a good system to be solved numerically. The solutions obtained for an ill-conditioned system must always be taken with considerable scepticism.
To estimate the good or bad conditioning of a system, we use the condition number, which we defined in the chapter \ref{ch:numpy} in section \ref{sec:SVD}, when talking about SVD factorisation. The condition number of a matrix is the quotient of its largest and smallest singular values. The closer the condition number is to $1$, the better conditioned the matrix is, and the larger the condition number, the worse conditioned it is.
\switchcolumn
En Python dentro del paquete \texttt{linalg} de \texttt{numpy} está la función \texttt{cond} que nos permite obtener el número de condición de una matriz. Si lo aplicamos a la matriz de coeficientes del último ejemplo mostrado,
\switchcolumn
In Python, we can use the function \texttt{cond} inside the \texttt{linalg} module in \texttt{numpy} to compute the condition number of a matrix. We can apply to the last example coefficient matrix
\end{paracol}
\begin{minted}{python}
import numpy as np
A=np.array([[4,1],[2,0.499]])
np.linalg.cond(A)
Out[7]: 5312.250061755533
\end{minted}
\begin{paracol}{2}
El número está bastante alejado de uno, lo que, en principio, indica un mal condicionamiento del sistema.
Incidentalmente, podemos calcular la factorización svd de la matriz de coeficientes y dividir el valor singular mayor entre el menor para comprobar que el resultado es el mismo que nos da la función \texttt{cond},
\switchcolumn
The number is quite far from one, which, in principle, indicates a ill-condition of the system.
Incidentally, we can calculate the factorisation svd of the coefficient matrix and divide the largest singular value by the smallest to check that the result is the same as that given by the function \texttt{cond},
\end{paracol}
\begin{minted}{python}
[U,S,Vt]=np.linalg.svd(A)
S[0]/S[1]
Out[14]: 5312.250061755533
\end{minted}
\begin{paracol}{2}
\section{Métodos directos}
\subsection{Sistemas triangulares}
Vamos a empezar el estudio de los métodos directos por los algoritmos de resolución de los sistemas más simples posibles, aquellos cuya matriz de coeficientes es una matriz diagonal, triangular superior o triangular inferior.
\paragraph{Sistemas diagonales.} Un sistema diagonal es aquel cuya matriz de coeficientes es una matriz diagonal.
\switchcolumn
\subsection{Direct methods}
\subsection{Triangular systems}
We are going to begin the study of direct methods with the algorithms for solving the simplest possible systems, those whose coefficient matrix is a diagonal, upper triangular or lower triangular matrix.
\paragraph{ Diagonal systems.} A diagonal system is one whose coefficient matrix is a diagonal matrix.
\end{paracol}
\begin{equation*}
\left. \begin{aligned}
a_{11}&x_1=b_1\\
a_{22}&x_2=b_2\\
\cdots & \\
a_{nn}&x_n=b_n
\end{aligned}\right\} \Rightarrow \overbrace{\begin{pmatrix}
a_{11}& 0& \cdots & 0\\
0& a_{22}& \cdots & 0\\
\vdots & \vdots & \ddots & \vdots\\
0& 0& \cdots & a_{nn}
\end{pmatrix}}^A \cdot \overbrace{\begin{pmatrix}
x_1\\
x_2\\
\vdots \\
x_n
\end{pmatrix}}^x=\overbrace{\begin{pmatrix}
b_1\\
b_2\\
\vdots \\
b_n
\end{pmatrix}}^b
\end{equation*}
\begin{paracol}{2}
Su resolución es trivial, basta dividir cada término independiente por el elemento correspondiente de la diagonal de la matriz de coeficientes,
\begin{equation*}
x_i=\frac{b_i}{a_{ii}}
\end{equation*}
\switchcolumn
Its resolution is trivial, just divide each independent term by the corresponding element of the diagonal of the coefficient matrix,
\begin{equation*}
x_i=\frac{b_i}{a_{ii}}
\end{equation*}
\switchcolumn
Para obtener la solución basta crear en Python un sencillo bucle \texttt{for},
\switchcolumn
To compute the solution it is enough to code a simple \texttt{for} loop,
\end{paracol}
\begin{minted}{python}
import numpy as np
def diag_sys(A,b):
[f,c]=np.shape(A)
x=np.zeros([f,1])
for i in range(f):
x[i]=b[i]/A[i,i]
return x
\end{minted}
\begin{paracol}{2}
\paragraph{Sistemas triangulares inferiores: método de sustituciones progresivas.} Un sistema triangular inferior de $n$ ecuaciones con $n$ incógnitas tendrá la forma general,
\switchcolumn
\paragraph{Lower triangular systems: method of progressive substitutions.} A lower triangular system of $n$ equations with $n$ unknowns will have the general form,
\end{paracol}
\begin{equation*}
\left. \begin{aligned}
a_{11}&x_1=b_1\\
a_{21}&x_1+a_{22}x_2=b_2\\
\cdots & \\
a_{n1}&x_1+a_{n2}x_2+\cdots +a_{nn}x_n=b_n
\end{aligned}\right\} \Rightarrow \overbrace{\begin{pmatrix}
a_{11}& 0& \cdots & 0\\
a_{21}& a_{22}& \cdots & 0\\
\vdots & \vdots & \ddots & \vdots\\
a_{n1}& a_{n2}& \cdots & a_{nn}
\end{pmatrix}}^A \cdot \overbrace{\begin{pmatrix}
x_1\\
x_2\\
\vdots \\
x_n
\end{pmatrix}}^x=\overbrace{\begin{pmatrix}
b_1\\
b_2\\
\vdots \\
b_n
\end{pmatrix}}^b
\end{equation*}
\begin{paracol}{2}
El procedimiento para resolverlo a \emph{mano} es muy sencillo,
despejamos la primera incógnita de la primera ecuación,
\begin{equation*}
x_1=\frac{b_1}{a_{11}}
\end{equation*}
\switchcolumn
The procedure to solve to \emph{hand} is very simple,
we clear the first unknown from the first equation,
\begin{equation*}
x_1=\frac{b_1}{a_{11}}
\end{equation*}
\switchcolumn
A continuación sustituimos este resultado en la segunda ecuación, y despejamos $x_2$,
\begin{equation*}
x_2=\frac{b_2-a_{21}x_1}{a_{22}}
\end{equation*}
\switchcolumn
Next, we substitute this result in the second equation and clear $x_2$
\begin{equation*}
x_2=\frac{b_2-a_{21}x_1}{a_{22}}
\end{equation*}
\switchcolumn
De cada ecuación vamos obteniendo una componente del vector solución, sustituyendo las soluciones obtenidas en las ecuaciones anteriores, así cuando llegamos a la ecuación $i$,
\begin{equation*}
x_i=\frac{b_i-\sum_{j=1}^{i-1}a_{ij}x_j}{a_{ii}}
\end{equation*}
\switchcolumn
From each equation we obtain a component of the solution vector, substituting the solutions obtained in the previous equations, so when we arrive at the equation $i$,
\begin{equation*}
x_i=\frac{b_i-\sum_{j=1}^{i-1}a_{ij}x_j}{a_{ii}}
\end{equation*}
\switchcolumn
Si repetimos este mismo proceso hasta llegar a la última ecuación del sistema, $n$, habremos obtenido la solución completa.
EL siguiente código calcula la solución de un sistema triangular inferior mediante sustituciones progresivas,
\switchcolumn
If we repeat this same process until we reach the last equation of the system, $n$, we will have obtained the complete solution.
The following code calculates the solution of a lower triangular system by progressive substitutions,
\end{paracol}
\begin{minted}{python}
import numpy as np
def progressive(A,b):
''' This function computes the solution of a lower equation system using
progressive substitution. It receives the coefficient matriz A and the
independent term vector b. It returns the vector solution x
'''
# Coefficient matrix size. Return error if not square
[f,c]=np.shape(A)
if f!=c:
print("A is not square")
return
# To build the solution vector x
x=np.zeros(f)
x=b.copy()
for i in range(f):
'''The inner block subtracts to the independent term the previous solution
multiplied by the correspondent coefficient'''
for j in range(0,i):
x[i]-=x[j]*A[i,j]
'''Finaly divide the result by the diagonal coefficient'''
x[i]=(x[i])/A[i,i]
return x
\end{minted}
\begin{paracol}{2}
\paragraph{Sistemas triangulares superiores: método de sustituciones regresivas.} En este caso, el sistema general de $n$ ecuaciones con $n$ incógnitas tendrá la forma general,
\switchcolumn
\paragraph{Upper triangular systems: method of backward substitutions.} In this case, the general system of $n$ equations with $n$ unknowns will have the general form,
\end{paracol}
\begin{equation*}
\left. \begin{aligned}
a_{11}x_1+a_{12}x_2+\cdots +a_{1n}x_n=b_1\\
a_{22}x_2+\cdots +a_{2n}x_n=b_2\\
\cdots \\
a_{nn}x_n=b_n
\end{aligned}\right\} \Rightarrow \overbrace{\begin{pmatrix}
a_{11}& a_{12}& \cdots & a_{1n}\\
0& a_{22}& \cdots & a_{2n}\\
\vdots & \vdots & \ddots & \vdots\\
0& 0& \cdots & a_{nn}
\end{pmatrix}}^A \cdot \overbrace{\begin{pmatrix}
x_1\\
x_2\\
\vdots \\
x_n
\end{pmatrix}}^x=\overbrace{\begin{pmatrix}
b_1\\
b_2\\
\vdots \\
b_n
\end{pmatrix}}^b
\end{equation*}
\begin{paracol}{2}
El método de resolución es idéntico al de un sistema triangular inferior, simplemente que ahora, empezamos a resolver por la última ecuación,
\begin{equation*}
x_n=\frac{b_n}{a_{nn}}
\end{equation*}
Y seguimos sustituyendo hacia arriba,
\begin{equation*}
x_{n-1}=\frac{b_{n-1}-a_{(n-1)n}x_{n}}{a_{(n-1)(n-1)}}
\end{equation*}
\begin{equation*}
x_i=\frac{b_i-\sum_{j=i+1}^{n}a_{ij}x_j}{a_{ii}}
\end{equation*}
\switchcolumn
The method of solution is identical to that of a lower triangular system, except that now, we start solving for the last equation,
\begin{equation*}
x_n=\frac{b_n}{a_{nn}}
\end{equation*}
And we keep substituting upwards,
\begin{equation*}
x_{n-1}=\frac{b_{n-1}-a_{(n-1)n}x_{n}}{a_{(n-1)(n-1)}}
\end{equation*}
\begin{equation*}
x_i=\frac{b_i-\sum_{j=i+1}^{n}a_{ij}x_j}{a_{ii}}
\end{equation*}
\switchcolumn
El código para implementar este método es similar al de las sustituciones progresivas. Se deja como ejercicio el construir una función en Python que calcule la solución de un sistema triangular superior por el método de las sustituciones regresivas.
\switchcolumn
The code to implement this method is similar to that of forward substitutions. It is left as an exercise to build a Python function that calculates the solution of an upper triangular system by the method of backward substitutions.
\switchcolumn
\subsection{Métodos basados en las factorizaciones}
Puesto que sabemos como resolver sistemas triangulares, una manera de resolver sistemas más complejos sería encontrar métodos para reducirlos a sistemas triangulares. De este modo evitamos invertir la matriz de coeficientes y los posibles problemas de estabilidad numérica derivados de dicha operación. Si podemos expresar la matriz $A$ como el producto de matrices diagonales o triangulares podremos resolver el sistema usando los métodos anteriores.
\textbf{Factorizar} una matriz es descomponer la misma en el producto de dos o más matrices de alguna forma canónica.
\switchcolumn
\subsection{Methods based on factorisations}
Since we know how to solve triangular systems, one way to solve more complex systems would be to find methods to reduce them to triangular systems. In this way we avoid inverting the matrix of coefficients and the possible problems of numerical stability derived from such an operation. If we can express the matrix $A$ as the product of diagonal or triangular matrices we can solve the system using the above methods.
\textbf{To factorise} a matrix is to decompose it into the product of two or more matrices of some canonical form.
\switchcolumn
\paragraph{Factorización LU.} La factorización LU consiste en factorizar una matriz en el producto de dos, una triangular inferior $L$ y una triangular superior $U$. La factorización puede incluir pivoteo de filas, para alcanzar una solución numéricamente estable. En este caso la factorización LU toma la forma,
\begin{equation*}
P^T\cdot A = L\cdot U
\end{equation*}
Donde $P$ representa una matriz de permutaciones.
Podemos verlo también de otra manera, $A=P \cdot L \cdot U$ ya que al ser $P$ una matriz de permutación es invertible y $P^{-1}=P^T$.
\switchcolumn
\paragraph{LU factorisation}. LU factorisation consists of factoring a matrix into the product of two, a lower triangular $L$ and an upper triangular $U$. The factorisation could include pivoting rows, to achieve a numerically stable solution. In this case the LU factorisation takes the form,
\begin{equation*}
P^T \cdot A = L\cdot U
\end{equation*}
Where $P$ represents a matrix of permutations.
We can also look at it in another way, $A=P \cdot L \cdot U$, since $P$ is a permutation matrix and $P^{-1}=P^T$.
\switchcolumn
Supongamos que queremos resolver un sistema de $n$ ecuaciones lineales con $n$ incógnitas que representamos genéricamente en forma matricial, como siempre,
\begin{equation*}
A\cdot x=b
\end{equation*}
Si calculamos la fatorización LU de su matriz de coeficientes,
\begin{equation*}
A \rightarrow A = P\cdot L\cdot U
\end{equation*}
\switchcolumn
Suppose we want to solve a system of $n$ linear equations with $n$ unknowns that we represent generically in matrix form, as usual,
\begin{equation*}
A\cdot x=b
\end{equation*}
If we compute the LU factorisation of the coefficient matrix,
\begin{equation*}
A \rightarrow A = P\cdot L\cdot U
\end{equation*}
\switchcolumn
Podemos transformar nuestro sistema de ecuaciones en uno equivalente sustituyendo $A$ por su descomposición.
\begin{equation*}
A\cdot x=b\rightarrow P\cdot L \cdot U \cdot x= b
\end{equation*}
\switchcolumn
We can transform our system of equations into an equivalent replacing $A$ by its lu factorisation,
\begin{equation*}
A\cdot x=b\rightarrow P\cdot L \cdot U \cdot x= b
\end{equation*}
\switchcolumn
Para poder resolver el sistema usando sustituciones progresivas y regresivas vamos a multiplicar ambos términos de la ecuación por $P^{-1}$, recordando que $P^{-1}=P^T$
\begin{equation*}
P^{-1} \cdot P\cdot L \cdot U \cdot x=P^{-1}\cdot b \rightarrow L\cdot U \cdot x= P^T\cdot b
\end{equation*}
\switchcolumn
In order to solve the system using progressive and reversible substitutions we will multiply both terms of the equation by $P^{-1}$, remembering that $P^{-1}=P^T$.
\begin{equation*}
P^{-1} \cdot P\cdot L \cdot U \cdot x=P^{-1}\cdot b \rightarrow L\cdot U \cdot x= P^T\cdot b
\end{equation*}
\switchcolumn
El nuevo sistema puede resolverse en dos pasos empleando sustituciones regresivas y sustituciones progresivas. Para ello, asociamos el producto $U\cdot x$, a un vector de incógnitas auxiliar al que llamaremos $z$,
\begin{equation*}
U\cdot x=z
\end{equation*}
\switchcolumn
The new system can be solved in two steps using backward and forward substitutions. To do this, we associate the product $U \cdot x$, to a vector of auxiliary unknowns which we will call $z$,
\switchcolumn
Si sustituimos nuestro vector auxiliar $z$ en la expresión matricial de nuestro sistema de ecuaciones,
\begin{equation*}
L\cdot \overbrace{U\cdot x}^z=P^T\cdot b \rightarrow L\cdot z=P^T\cdot b
\end{equation*}
\switchcolumn
If we substitute our auxiliary vector $z$ into the matrix expression of our system of equations,
\begin{equation*}
L\cdot \overbrace{U\cdot x}^z=P^T\cdot b \rightarrow L\cdot z=P^T\cdot b
\end{equation*}
\switchcolumn
El sistema resultante es triangular inferior, por lo que podemos resolverlo por sustituciones progresivas, y obtener de este modo los valores de $z$. Podemos finalmente obtener la solución del sistema a través de la definición de $z$; $U\cdot x =z$, se trata de un sistema triangular superior, que podemos resolver mediante sustituciones regresivas.
\switchcolumn
The resulting system is lower triangular, so we can solve it by forward substitutions, and thus obtain the values of $z$. We can finally obtain the solution of the system through the definition of $z$; $U \cdot x =z$, it is an upper triangular system, which we can solve by backward substitutions.
\switchcolumn
Veamos un ejemplo. Supongamos que queremos resolver el sistema de ecuaciones lineales,
\switchcolumn
Let us look at an example. Suppose we want to solve the system of linear equations,
\end{paracol}
\begin{equation*}
\begin{pmatrix}
1& 3& 2\\
2& -1& 1\\
1& 4& 3
\end{pmatrix}\cdot \begin{pmatrix}
x_1\\
x_2\\
x_3
\end{pmatrix}=\begin{pmatrix}
13\\
3\\
18
\end{pmatrix}
\end{equation*}
\begin{paracol}{2}
En primer lugar deberíamos comprobar que la matriz de coeficiente esta bien condicionada,
\switchcolumn
First we should check that the coefficient matrix is well conditioned,
\end{paracol}
\begin{minted}{python}
import numpy as np
A=np.array([[1, 3, 2],[2, -1, 1],[1, 4, 3]])
cond=np.linalg.cond(A)
print(cond)
24.382675394986972
\end{minted}
\begin{paracol}{2}
No es un valor grande, con lo que podemos considerar que $A$ está bien condicionada.
Calculamos la factorización LU de la matriz de coeficientes, para ello podemos emplear el método \texttt{lu} del paquete de álgebra lineal de scipy. Este método nos devuelve las matrices $P$, $L$ y $U$ que satisfacen que $A=P \cdot L \cdot U$
\switchcolumn
It is not a large value, so we can consider that $A$ is well conditioned.
We compute the LU factorisation of the coefficient matrix, for this we can use the \texttt{lu} method of the scipy linear algebra package. This method returns the matrices $P$, $L$ and $U$ that satisfy that $A=P \cdot L \cdot U$
\end{paracol}
\begin{minted}{python}
import numpy as np
import scipy as sc
A=np.array([[1, 3, 2],[2, -1, 1],[1, 4, 3]])
b=np.array([[13],[3],[18]])
cond=np.linalg.cond(A)
P,L,U=sc.linalg.lu(A)
\end{minted}
\begin{minted}{python}
L: [[1. 0. 0. ]
[0.5 1. 0. ]
[0.5 0.77777778 1. ]]
U: [[ 2. -1. 1. ]
[ 0. 4.5 2.5 ]
[ 0. 0. -0.44444444]]
P: [[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]]
\end{minted}
\begin{paracol}{2}
A continuación debemos aplicar la matriz de permutaciones transpuesta, al vector de términos independientes del sistema, para poder construir el sistema equivalente $L\cdot U \cdot x=P^T\cdot b$,
\switchcolumn
Next we must apply the transpose matrix of permutations to the vector of independent terms of the system, in order to construct the equivalent system $L\cdot U \cdot x= P^T\cdot b$,
\end{paracol}
\begin{minted}{python}
Pb=np.transpose(P).dot(b)
print("Pb: ",Pb)
\end{minted}
\begin{minted}{python}
Pb: [[ 3.]
[18.]
[13.]]
\end{minted}
\begin{paracol}{2}
Empleamos la matriz $L$ obtenida y el producto $bp=P^T\cdot b$ que acabamos de calcular, para obtener, por sustituciones progresivas, el vector auxiliar $z$ descrito más arriba. Empleamos para ello la función \texttt{progressive}, cuyo código incluimos en la sección anterior,
\switchcolumn
We use the matrix $L$ obtained and the product $bp=P^T\cdot b$ that we have just calculated, to obtain, by progressive substitutions, the auxiliary vector $z$ described above. To do this we use the function \texttt{progressive}, whose code is included in the previous section,
\end{paracol}
\begin{minted}{python}
z=progressive(L, bP)
print("z:",z)
\end{minted}
\begin{minted}{python}
z: [[ 3. ]
[16.5 ]
[-1.33333333]]
\end{minted}
\begin{paracol}{2}
Finalmente, podemos obtener la solución del sistema sin más que aplicar el método de las sustituciones regresiva a la matriz $U$ y al vector auxiliar $z$ que acabamos de obtener,\footnote{La función \texttt{regressive} no se ha suministrado. Su construcción se ha dejado como ejercicio en la sección anterior.}
\switchcolumn
Finally, we can obtain the solution of the system by simply applying the method of regressive substitutions to the matrix $U$ and the auxiliary vector $z$ that we have just obtained,\footnote{ The function \texttt{regressive} has not been supplied. Its construction has been left as an exercise in the previous section.}
\end{paracol}
\begin{minted}{python}
x=regressive(U, z)
print("x:",x)
\end{minted}
\begin{minted}{python}
x: [[1.]
[2.]
[3.]]
\end{minted}
\begin{paracol}{2}
Para comprobar que la solución es correcta basta multiplicar la matriz de coeficientes del sistema original por el resultado obtenido para $x$ y comprobar que obtenemos como resultado el vector de términos independientes.
\switchcolumn
To check that the solution is correct, it is enough to multiply the matrix of coefficients of the original system by the result obtained for $x$ and check that we obtain as a result the vector of independent terms.
\end{paracol}
\begin{minted}{python}
print(A.dot(x))
\end{minted}
\begin{minted}{python}
[[13.]
[ 3.]
[18.]]
\end{minted}
\begin{flalign*}