Home python How to effectively calculate the determinant of the matrix?

# How to effectively calculate the determinant of the matrix?

Author

Date

Category

The code below considers the determinant of the matrix 20×20 by the method of minor and writes the time that it needed to calculate. But he considers such a big matrix for a very long time, a few hours …

``````import time, random
From Random Import Randint
Ic = [0 for i in Range (10)]
DEF MINOR (Array):
RETURN ARRAY   * Array   - Array   * Array  
Def Division (Array):
IF LEN (Array ) & gt; 2:
Result = 0.
For i in Range (Len (Array )):
new_arr = []
For j in Range (Len (Array )):
if j! = i:
new_arr.append ([Array [j] [k] for k in range (1, len (array )]))
Result + = Division (New_Arr) * Array [i]  * (-1 + 2 * ((i + 1)% 2))
Return Result
ELSE:
Return Minor (Array)
N = 20.
Result = 0.
Print (F "\ Nn: \ t {n} \ n")
Timer = time.time ()
MATRIX = [[RANDINT (0, 9) FOR ROW IN RANGE (N)] FOR ROW IN RANGE (N)]
Print (F "RESULT: \ T {Division (Matrix)}")
For i in Range (N):
Print (Matrix [i])
Print (F "TIME: \ T {time.time () - Timer}")
``````

How can this be optimized?

How can this be optimized?

Use the `NUMPY `module:

``````in : Import Numpy As NP # Pip Install NUMPY
In : a = np.random.rand (20, 20)
In : res = np.linalg.det (a)
In : Res
Out : 0.09252260373277807
``````

Working hours for the matrix 20×20:

``````in :% timeit np.linalg.det (a)
27.6 μS ± 37 NS PER LOOP (Mean ± Std. Dev. Of 7 Runs, 10,000 Loops Each)
``````

Calculation of the determinant through minors has factorial complexity and unsuitable for N & GT; 10.

Instead, it is worth implementing LU decomposition matrix (cubic complexity) and then calculate the determinant as a product of diagonal elements L and U matrices.

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.