For a given matrix, return the determinant and the permanent of the matrix.

The determinant is given by

 



det
(
A
)
=

∑

σ


sgn
⁡
(
σ
)

∏

i
=
1


n



M

i
,

σ

i






{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}


while the permanent is given by

 



perm
⁡
(
A
)
=

∑

σ



∏

i
=
1


n



M

i
,

σ

i






{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}


In both cases the sum is over the permutations 



σ


{\displaystyle \sigma }

 of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)

More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.



Related task

 Permutations by swapping


F s_permutations(seq)
   V items = [[Int]()]
   L(j) seq
      [[Int]] new_items
      L(item) items
         V i = L.index
         I i % 2
            new_items [+]= (0 .. item.len).map(i -> @item[0 .< i] [+] [@j] [+] @item[i ..])
         E
            new_items [+]= (item.len .< -1).step(-1).map(i -> @item[0 .< i] [+] [@j] [+] @item[i ..])
      items = new_items
 
   R enumerate(items).map((i, item) -> (item, I i % 2 {-1} E 1))
 
F det(a)
   V result = 0.0
   L(sigma, _sign_) s_permutations(Array(0 .< a.len))
      V x = Float(_sign_)
      L(i) 0 .< a.len
         x *= a[i][sigma[i]]
      result += x
   R result
 
F perm(a)
   V result = 0.0
   L(sigma, _sign_) s_permutations(Array(0 .< a.len))
      V x = 1.0
      L(i) 0 .< a.len
         x *= a[i][sigma[i]]
      result += x
   R result
 
V a = [[1.0, 2.0],
       [3.0, 4.0]]
 
V b = [[Float( 1),  2,  3,  4],
       [Float( 4),  5,  6,  7],
       [Float( 7),  8,  9, 10],
       [Float(10), 11, 12, 13]]
 
V c = [[Float( 0),  1,  2,  3,  4],
       [Float( 5),  6,  7,  8,  9],
       [Float(10), 11, 12, 13, 14],
       [Float(15), 16, 17, 18, 19],
       [Float(20), 21, 22, 23, 24]]
 
print(‘perm: ’perm(a)‘ det: ’det(a))
print(‘perm: ’perm(b)‘ det: ’det(b))
print(‘perm: ’perm(c)‘ det: ’det(c))