Determinant and permanent: Difference between revisions

add FreeBASIC
(Added 11l)
(add FreeBASIC)
Line 1,007:
end program f
</lang>
 
=={{header|FreeBASIC}}==
<lang freebasic>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 )</lang>
{{out}}<pre>
-2 10
0 29556
0 6778800
</pre>
 
=={{header|FunL}}==
781

edits