18.2: Algorithm to calculate the determinant
- Page ID
- 67883
Consider the following recursive algorithm (algorithm that calls itself) to determine the determinate of a \(n \times n\) matrix \(A\) (denoted \(\left| A \right|\)), which is the sum of the products of the elements of any row or column. i.e.:
\[i\text{th row expansion: } |A| = a_{i1}C_{i1} + a_{i2}C_{i2} + \ldots + a_{in}C_{in} \nonumber \]
\[j\text{th column expansion: } |A| = a_{1j}C_{1j} + a_{2j}C_{2j} + \ldots + a_{nj}C_{nj} \nonumber \]
where \(C_{ij}\) is the cofactor of \(a_{ij}\) and is given by:
\[ C_{ij} = (-1)^{i+j}|M_{ij}| \nonumber \]
and \(M_{ij}\) is the matrix that remains after deleting row \(i\) and column \(j\) of \(A\).
Here is some code that tries to implement this algorithm.
The following code generates an \(n \times n\) matrix with random values from 0 to 10.
Run the code multiple times to get different matrices:
Use the randomly generated matrix (\(A\)) to test the above mydet
function and compare your result to the numpy.linalg.det
function.
Are the answers to mydet
and numpuy.linalg.det
exactly the same every time you generate a different random matrix? If not, explain why.
On line 26 of the above code, you can see that algorithm calls itself. Explain why this doesn’t run forever.