LU decomposition: Difference between revisions

m
→‎{{header|Raku}}: bit more idiomatic
m (→‎{{header|Phix}}: added syntax colouring, made p2js compatible)
m (→‎{{header|Raku}}: bit more idiomatic)
Line 3,963:
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015-11-20}}
Translation of Ruby.
 
Translation of Ruby.
<lang perl6>for ( [1, 3, 5], # Test Matrices
[2, 4, 7],
Line 3,977 ⟶ 3,976:
-> @test {
say-it 'A Matrix', @test;
say-it( $_.[0], @($_.[1]) ) for 'P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix' Z, lu @test;
}
 
sub lu (@a) {
die unless @a.&is-square;
my $n = +@a;
my @P = pivotize @a;
my @Aʼ = mmult @P, @a;
my @L = matrix-ident $n;
my @U = matrix-zero $n;
for ^$n X ^$n -> ($i,$j) {
if $j $i { @U[$i][;$j] = @AP[$i][;$j] - [+] map { @U[$_][;$j] *× @L[$i][;$_] }, ^$i }
for ^$n -> $j {
else if { @L[$i;$j] >= (@AP[$i;$j] - [+] map { @U[$_;$j] × @L[$i;$_] }, ^$j) / @U[$j;$j] }
@U[$i][$j] = @Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$i
} else {
@L[$i][$j] = (@Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$j) / @U[$j][$j];
}
}
 
}
return @P, @Aʼ, @L, @U;
}
 
sub pivotize (@m) {
my $size = +@m;
my @id = matrix-ident $size;
for ^$size -> $i {
my $max = @m[$i][;$i];
my $row = $i;
for $i ..^ $size -> $j {
if @m[$j][;$i] > $max {
$max = @m[$j][;$i];
$row = $j;
}
}
@id[$row, $i] = @id[$i, $row] if $row != $i {;
@id[$row, $i] = @id[$i, $row]
}
}
@id
}
 
sub is-square (@m) { so @m == all @m[*] }
 
sub matrix-zero ($n, $m = $n) { map { [ flat 0 xx $n ] }, ^$m }
Line 4,028 ⟶ 4,019:
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
@p[$r][;$c] += @a[$r][;$_] *× @b[$_][;$c] for ^@b;
}
@p
Line 4,035 ⟶ 4,026:
sub rat-int ($num) {
return $num unless $num ~~ Rat;
return $num.narrow if $num.narrow.WHAT ~~ Int;
$num.nude.join: '/';
 
}
 
2,392

edits