Cramer's rule: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
SqrtNegInf (talk | contribs) m (→{{header|Raku}}: some sigil-less, other changes for code-readability) |
||
Line 2,333: | Line 2,333: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
<syntaxhighlight lang="raku" line>sub det(@matrix) { |
<syntaxhighlight lang="raku" line>sub det(@matrix) { |
||
my @a = @matrix.map: { [|$_] }; |
my @a = @matrix.map: { [|$_] }; |
||
my $sign = |
my $sign = 1; |
||
my $pivot = 1; |
my $pivot = 1; |
||
for ^@a -> |
for ^@a -> \k { |
||
my @r = ( |
my @r = (k+1 ..^ @a); |
||
my $previous-pivot = $pivot; |
my $previous-pivot = $pivot; |
||
if 0 == ($pivot = @a[ |
if 0 == ($pivot = @a[k;k]) { |
||
(my |
(my \s = @r.first: { @a[$_;k] != 0 }) // return 0; |
||
(@a[ |
(@a[s], @a[k]) = (@a[k], @a[s]); |
||
my $pivot = @a[ |
my $pivot = @a[k;k]; |
||
$sign = -$sign; |
$sign = -$sign; |
||
} |
} |
||
for @r X @r -> ( |
for @r X @r -> (\i,\j) { |
||
((@a[ |
((@a[i;j] ×= $pivot) -= @a[i;k]×@a[k;j]) /= $previous-pivot; |
||
} |
} |
||
} |
} |
||
$sign |
$sign × $pivot |
||
} |
} |
||
sub cramers_rule(@A, @terms) { |
sub cramers_rule(@A, @terms) { |
||
gather for ^@A -> |
gather for ^@A -> \i { |
||
my @Ai = @A.map: { [|$_] }; |
my @Ai = @A.map: { [|$_] }; |
||
for ^@terms -> |
for ^@terms -> \j { |
||
@Ai[ |
@Ai[j;i] = @terms[j]; |
||
} |
} |
||
take det(@Ai); |
take det(@Ai); |
||
Line 2,369: | Line 2,369: | ||
); |
); |
||
my @free_terms = |
my @free_terms = <-3 -32 -47 49>; |
||
my ($w, $x, $y, $z) = |
my ($w, $x, $y, $z) = cramers_rule(@matrix, @free_terms); |
||
("w = $w", "x = $x", "y = $y", "z = $z").join("\n").say;</syntaxhighlight> |
|||
say "w = $w"; |
|||
say "x = $x"; |
|||
say "y = $y"; |
|||
say "z = $z";</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |