Reduced row echelon form: Difference between revisions
Content deleted Content added
m →{{header|Maxima}}: was wrong |
|||
Line 2,593: | Line 2,593: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{works with|Ruby|1.9.3}} |
|||
<lang ruby>require 'rational' |
|||
⚫ | |||
⚫ | |||
def reduced_row_echelon_form(ary) |
def reduced_row_echelon_form(ary) |
||
lead = 0 |
lead = 0 |
||
rows = ary.size |
rows = ary.size |
||
cols = ary[0].size |
cols = ary[0].size |
||
rary = |
rary = convert_to(ary, :to_r) # use rational arithmetic |
||
catch :done do |
catch :done do |
||
rows.times do |r| |
rows.times do |r| |
||
Line 2,617: | Line 2,616: | ||
# normalize row r |
# normalize row r |
||
v = rary[r][lead] |
v = rary[r][lead] |
||
rary[r].collect! {|x| x / |
rary[r].collect! {|x| x / v} |
||
# reduce other rows |
# reduce other rows |
||
rows.times do |i| |
rows.times do |i| |
||
Line 2,630: | Line 2,629: | ||
end |
end |
||
⚫ | |||
def convert_to_rational(ary) |
|||
⚫ | |||
new = [] |
|||
ary. |
ary.each_with_object([]) do |row, new| |
||
new << |
new << row.collect {|elem| elem.send(type)} |
||
end |
end |
||
new |
|||
end |
end |
||
class Rational |
|||
⚫ | |||
alias _to_s to_s |
|||
⚫ | |||
def to_s |
|||
denominator==1 ? numerator.to_s : _to_s |
|||
ary.each_index do |row| |
|||
new << ary[row].collect {|elem| elem.send(type)} |
|||
end |
end |
||
new |
|||
end |
end |
||
Line 2,650: | Line 2,646: | ||
max = m[0].collect {-1} |
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| max[i] = [max[i], row[i].to_s.length].max}} |
||
m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i] |
m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i]}; puts} |
||
end |
end |
||
Line 2,658: | Line 2,654: | ||
[-2, 0, -3, 22] |
[-2, 0, -3, 22] |
||
] |
] |
||
print_matrix |
print_matrix reduced_row_echelon_form(mtx) |
||
puts |
puts |
||
mtx = [ |
mtx = [ |
||
Line 2,667: | Line 2,663: | ||
] |
] |
||
reduced = reduced_row_echelon_form(mtx) |
reduced = reduced_row_echelon_form(mtx) |
||
print_matrix |
print_matrix reduced |
||
print_matrix convert_to(reduced, :to_f)</lang> |
print_matrix convert_to(reduced, :to_f)</lang> |
||
⚫ | |||
{{out}} |
|||
<pre> |
|||
⚫ | |||
0 1 0 1 |
0 1 0 1 |
||
0 0 1 -2 |
0 0 1 -2 |
||
Line 2,676: | Line 2,675: | ||
0 1 0 5/3 |
0 1 0 5/3 |
||
0 0 1 1 |
0 0 1 1 |
||
1.0 0.0 0.0 0. |
1.0 0.0 0.0 0.6666666666666666 |
||
0.0 1.0 0.0 |
0.0 1.0 0.0 1.6666666666666667 |
||
0.0 0.0 1.0 1.0 |
0.0 0.0 1.0 1.0 |
||
</pre> |
|||
=={{header|Sage}}== |
=={{header|Sage}}== |