Jump to content

Reduced row echelon form: Difference between revisions

Line 2,593:
 
=={{header|Ruby}}==
{{works with|Ruby|1.9.3}}
<lang ruby>require 'rational'
<lang ruby># returns an 2-D array where each element is a Rational
 
# returns an 2-D array where each element is a Rational
def reduced_row_echelon_form(ary)
lead = 0
rows = ary.size
cols = ary[0].size
rary = convert_to_rationalconvert_to(ary, :to_r) # use rational arithmetic
catch :done do
rows.times do |r|
Line 2,617 ⟶ 2,616:
# normalize row r
v = rary[r][lead]
rary[r].collect! {|x| x /= v}
# reduce other rows
rows.times do |i|
Line 2,630 ⟶ 2,629:
end
 
# type should be one of :to_s, :to_i, :to_f, :to_r
def convert_to_rational(ary)
def convert_to(ary, type)
new = []
ary.each_indexeach_with_object([]) do |row, new|
new << ary[row].collect {|elem| Rational(elem.send(type)}
end
new
end
 
class Rational
# type should be one of :to_s, :to_i, :to_f, :to_r
alias _to_s to_s
def convert_to(ary, type)
newdef = []to_s
denominator==1 ? numerator.to_s : _to_s
ary.each_index do |row|
new << ary[row].collect {|elem| elem.send(type)}
end
new
end
 
Line 2,650 ⟶ 2,646:
max = m[0].collect {-1}
m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}}
m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i].to_s}; puts ""}
end
 
Line 2,658 ⟶ 2,654:
[-2, 0, -3, 22]
]
print_matrix convert_to(reduced_row_echelon_form(mtx), :to_s)
puts ""
 
mtx = [
Line 2,667 ⟶ 2,663:
]
reduced = reduced_row_echelon_form(mtx)
print_matrix convert_to(reduced, :to_r)
print_matrix convert_to(reduced, :to_f)</lang>
 
<pre>1 0 0 -8
{{out}}
<pre>
<pre>1 0 0 -8
0 1 0 1
0 0 1 -2
Line 2,676 ⟶ 2,675:
0 1 0 5/3
0 0 1 1
1.0 0.0 0.0 0.6666666666666676666666666666666
0.0 1.0 0.0 1.666666666666676666666666666667
0.0 0.0 1.0 1.0</pre>
</pre>
 
=={{header|Sage}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.