LU decomposition: Difference between revisions

(Updated D entry)
Line 1,964:
if j >= i
# upper
u[i][j] = tmp[i,j] - (0 ... i-1).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}
else
# lower
l[i][j] = (tmp[i,j] - (0 ... j-1).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j]
end
end
Line 1,973:
[ Matrix[*l], Matrix[*u], p ]
end
 
def get_pivot
raise ArgumentError, "must be square" unless square?
Line 1,990:
Matrix[*id]
end
 
def pretty_print(format, head=nil)
puts head if head
each_with_index do |val, i, j|
puts each_slice(column_size).map{|row| print "#{format} "*row_size % valrow}
puts "" if j==column_size-1
end
end
end
 
puts "Example 1:"
a = Matrix[[1, 3, 5],
[2, 4, 7],
[1, 1, 0]]
puts "A"; a.pretty_print(" %2d", "A")
l, u, p = a.lu_decomposition
puts "U"; ul.pretty_print(" %8.5f", "L")
puts "L"; lu.pretty_print(" %8.5f", "U")
puts "P"; p.pretty_print(" %d", "P")
 
puts "\nExample 2:"
a = Matrix[[11, 9,24,2],
[ 1, 5, 2,6],
[ 3,17,18,1],
[ 2, 5, 7,1]]
puts "A"; a.pretty_print(" %2d", "A")
l, u, p = a.lu_decomposition
puts "U"; ul.pretty_print(" %8.5f", "L")
puts "L"; lu.pretty_print(" %8.5f", "U")
puts "P"; p.pretty_print(" %d", "P")</lang>
 
{{out}}
output
<pre style="height: 40ex; overflow: scroll">A
Example 1:
1 3 5
A
2 4 7
1 1 03 5
2 end4 7
1 31 51 0
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
 
Example 2:
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1 </pre>
</pre>
 
Matrix has a <code>lup_decomposition</code> built-in method.
<lang ruby>l, u, p = a.lup_decomposition
l.pretty_print(" %8.5f", "L")
u.pretty_print(" %8.5f", "U")
p.pretty_print(" %d", "P")</lang>
Output is the same.
 
=={{header|Tcl}}==
Anonymous user