Chapter 2

f_02_02.jl

Gaussian elimination using LU factorization

Other versions: j_02_02.jl, nm22.jl


In [16]:
using NMfE

In [17]:
A=[10. 1. -5.;-20. 3. 20.;5. 3. 5.]


Out[17]:
3x3 Array{Float64,2}:
  10.0  1.0  -5.0
 -20.0  3.0  20.0
   5.0  3.0   5.0

In [18]:
b=[1., 2., 6.]


Out[18]:
3-element Array{Float64,1}:
 1.0
 2.0
 6.0

In [19]:
(lower, upper) = lufac(A)
# NMfE lufac(A) - lower
lower


Out[19]:
3x3 Array{Float64,2}:
  1.0  0.0  0.0
 -2.0  1.0  0.0
  0.5  0.5  1.0

In [20]:
# NMfE lufac(A) - upper
upper


Out[20]:
3x3 Array{Float64,2}:
 10.0  1.0  -5.0
  0.0  5.0  10.0
  0.0  0.0   2.5

In [21]:
# Check if we get A back
lower * upper


Out[21]:
3x3 Array{Float64,2}:
  10.0  1.0  -5.0
 -20.0  3.0  20.0
   5.0  3.0   5.0

In [22]:
subfor!(lower, b)
# Updated RHS
b


Out[22]:
3-element Array{Float64,1}:
 1.0
 4.0
 3.5

In [23]:
subbac!(upper, b)
# Solution vector:
b


Out[23]:
3-element Array{Float64,1}:
  1.0
 -2.0
  1.4

In [24]:
d = copy(b)
# Restore b
b=[1., 2., 6.];

In [25]:
c = A\b


Out[25]:
3-element Array{Float64,1}:
  1.0
 -2.0
  1.4

In [26]:
round(A * c, 14) == b


Out[26]:
true

In [27]:
round(c, 14) == d


Out[27]:
true

In [28]:
# Julia lufact(A)
f = lufact(A);

In [29]:
f[:L]


Out[29]:
3x3 Array{Float64,2}:
  1.0   0.0       0.0
 -0.25  1.0       0.0
 -0.5   0.666667  1.0

In [30]:
f[:U]


Out[30]:
3x3 Array{Float64,2}:
 -20.0  3.0   20.0    
   0.0  3.75  10.0    
   0.0  0.0   -1.66667