Reduced row echelon form: Difference between revisions

m
→‎{{header|Raku}}: house-keeping phase 1: split long entry into 3 sections, tidy up 1st section
m (→‎{{header|Raku}}: house-keeping phase 1: split long entry into 3 sections, tidy up 1st section)
Line 3,366:
=={{header|Raku}}==
(formerly Perl 6)
 
=== Following pseudocode ===
{{trans|Perl}}
{{works with|Rakudo|2018.03}}
<lang perl6>sub rref (@m) {
my ($lead, $rows, $cols) = 0, +@m, +@m[0];
return unless @m;
my ($lead, $rows, $cols) = 0, +@m, +@m[0];
 
for ^$rows -> $r {
return @m unless $lead < $cols or return @m;
my $i = $r;
until @m[$i;$lead] {
next unless ++$i == $rows or next;
$i = $r;
return @m if ++$lead == $cols and return @m;
}
@m[$i, $r] = @m[$r, $i] if $r != $i;
my@m[$r] »/=» $lv = @m[$r;$lead];
 
@m[$r] »/=» $lv;
for ^$rows -> $n {
next if $n == $r;
@m[$n] »-=» @m[$r] »*×» (@m[$n;$lead] // 0);
}
++$lead;
Line 3,394 ⟶ 3,393:
sub rat-or-int ($num) {
return $num unless $num ~~ Rat;
return $num.narrow if $num.narrow.WHAT ~~ Int;
$num.nude.join: '/';
}
Line 3,454 ⟶ 3,453:
 
{{out}}
<pre style="height:70ex">
<pre>
Original Matrix
1 2 -1 -4
Line 3,464 ⟶ 3,463:
0 1 0 1
0 0 1 -2
 
 
 
Original Matrix
Line 3,476 ⟶ 3,473:
0 1 0 -217/6
0 0 1 -125/6
 
 
 
Original Matrix
Line 3,492 ⟶ 3,487:
0 0 0 0 0 0
0 0 0 0 0 0
 
 
 
Original Matrix
Line 3,534 ⟶ 3,527:
</pre>
 
=== Row operations, procedural code ===
Re-implemented without the pseudocode, expressed as elementary matrix row operations. SeeFollow links for background on
[http://unapologetic.wordpress.com/2009/08/27/elementary-row-and-column-operations/ row operations]
and
[http://unapologetic.wordpress.com/2009/09/03/reduced-row-echelon-form/ reduced row echelon form]
 
First, a procedural version:
<lang perl6>sub swap_rows ( @M, $r1, $r2 ) { @M[ $r1, $r2 ] = @M[ $r2, $r1 ] };
sub scale_row ( @M, $scale, $r ) { @M[$r] = @M[$r] »*» $scale };
Line 3,573 ⟶ 3,566:
say @($_)».fmt(' %4g') for @M;</lang>
 
=== Row operations, object-oriented code ===
And the same code as previous section, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.
<lang perl6>class Matrix is Array {
method unscale_row ( @M: $scale, $row ) {
Line 3,617 ⟶ 3,611:
 
say @($_)».fmt(' %4g') for @($M);</lang>
 
Note that both versions can be simplified using Z+=, Z-=, X*=,
and X/= to scale and shear.
Currently, Rakudo has a bug related to Xop= and Zop=.
 
Note that the negative zeros in the output are innocuous,
and also occur in the Perl 5 version.
 
=={{header|REXX}}==
2,392

edits