Jump to content

Determinant and permanent: Difference between revisions

→‎{{header|Raku}}: add a test with a Hilbert matrix
(→‎{{header|Raku}}: Fix up some internal links)
(→‎{{header|Raku}}: add a test with a Hilbert matrix)
Line 1,909:
note "Not a square matrix" and return
if [||] map { @a.elems cmp @a[$_].elems }, ^@a;
sum σ_permutations([+^@a] ).race.map: {
my $permutation = .key;
my $term = $op eq 'perm' ?? 1 !! .value;
for $permutation.kv -> $i, $j { $term *= @a[$i][$j] };
$term
[}
}, σ_permutations [^@a];
}
 
########### Testinghelper subs ###########
sub hilbert-matrix (\h) {[(1..h).map(-> \n {[(n..^n+h).map: {(1/$_).FatRat}]})]}
 
sub rat-or-int ($num) {
return $num unless $num ~~ Rat|FatRat;
return $num.narrow if $num.narrow.WHAT ~~ Int;
$num.nude.join: '/';
 
sub say-it ($message, @array) {
saymy ''$max;
@array.map: {$max max= max $_».&rat-or-int.comb(/\S+/)».chars};
say '-' x 25"\n$message";
$_».&rat-or-int.fmt(" %{$max}s").put for @array;
}
 
########### Testing ###########
my @tests = (
[
Line 1,930 ⟶ 1,945:
[ 10, 11, 12, 13 ]
],
hilbert-matrix 7
[
[ 0, 1, 2, 3, 4 ],
[ 5, 6, 7, 8, 9 ],
[ 10, 11, 12, 13, 14 ],
[ 15, 16, 17, 18, 19 ],
[ 20, 21, 22, 23, 24 ]
]
);
 
sub dump (@matrix) {
say $_».fmt: "%3s" for @matrix;
say '';
 
for @tests -> @matrix {
say-it 'Matrix:', @matrix;
say "Determinant:\t", rat-or-int @matrix.&dumpm_arith: <det>;
say "DeterminantPermanent: \t", rat-or-int @matrix.&m_arith: <detperm>;
say "Permanent:'-' x \t", @matrix.&m_arith: <perm>40;
say '-' x 25;
}</lang>
 
'''Output'''
<pre>Matrix:
[ 1 2]
[ 3 4]
 
Determinant: -2
Permanent: 10
----------------------------------------
 
Matrix:
[ 1 2 3 4]
[ 4 5 6 7]
[ 7 8 9 10]
[ 10 11 12 13]
 
Determinant: 0
Permanent: 29556
----------------------------------------
 
Matrix:
[ 0 1 1/2 1/3 1/4] 1/5 1/6 1/7
[ 1/2 1/3 1/4 1/5 1/6 1/7 1/8 9]
1/3 1/4 [ 1/5, 1/6, 1/7, 1/8, 9 ],1/9
[ 10 11 12 13 14]
1/4 1/5 1/6 1/7 1/8 1/9 1/10
[ 15 16 17 18 19]
1/5 1/6 1/7 1/8 1/9 1/10 1/11
[ 20 21 22 23 24]
1/6 1/7 [1/8 0, 1,/9 2,1/10 3,1/11 4 ],1/12
 
1/7 1/8 1/9 1/10 1/11 1/12 1/13
Determinant: 0
Determinant: 1/2067909047925770649600000
Permanent: 6778800
Permanent: 29453515169174062608487/2067909047925770649600000
----------------------------------------</pre>
 
=={{header|REXX}}==
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.