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


sub make_S( M() as double, S() as double, i as uinteger, j as uinteger )
    'removes row j, column i from the matrix, stores result in S()
    dim as uinteger ii, jj, size=ubound(M), ix, jx
    for ii = 1 to size-1
        if ii<i then ix = ii else ix = ii + 1
        for jj = 1 to size-1
            if jj<j then jx = jj else jx = jj + 1
            S(ii, jj) = M(ix, jx)
        next jj
    next ii
end sub
 
function deperminant( M() as double, det as boolean ) as double
    'calculates the determinant or the permanent of a square matrix M
    'det = true  for determinant, false for permanent
    'assumes a square matrix
    dim as uinteger size = ubound(M,1), i
    dim as integer sign
    dim as double S(1 to size-1, 1 to size-1)
    dim as double ret = 0.0, inc
    if size = 1 then return M(1,1)                                       'matrices of size < 3 are easy to calculate
    if size = 2 and det then return M(1,1)*M(2,2) - M(1,2)*M(2,1)
    if size = 2         then return M(1,1)*M(2,2) + M(1,2)*M(2,1)
    for i = 1 to size
            if det then sign = (-1)^(i+1) else sign = 1                 'this bit is what distinguishes a determinant from a permanent
            make_S( M(), S(), i, 1 )
            inc = sign*M(i,1)*deperminant( S(), det )                   'recursively call on submatrices
            ret += inc
    next i
    return ret
end function
 
dim as double A(1 to 2, 1 to 2) = {{1,2},{3,4}}
 
dim as double B(1 to 4, 1 to 4) = {_
    {1,2,3,4}, {4,5,6,7}, {7,8,9,10}, {10,11,12,13} }
 
dim as double C(1 to 5, 1 to 5) = {_
     {  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 } }
 
print deperminant( A(), true ), deperminant( A(), false )
print deperminant( B(), true ), deperminant( B(), false )
print deperminant( C(), true ), deperminant( C(), false )