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 [0] [0] * Array [1] [1] - Array [1] [0] * Array [0] [1]
Def Division (Array):
  IF LEN (Array [0]) & gt; 2:
    Result = 0.
    For i in Range (Len (Array [0])):
      new_arr = []
      For j in Range (Len (Array [0])):
        if j! = i:
          new_arr.append ([Array [j] [k] for k in range (1, len (array [0])]))
      Result + = Division (New_Arr) * Array [i] [0] * (-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?


Answer 1, Authority 100%

How can this be optimized?

Use the NUMPY module:

in [32]: Import Numpy As NP # Pip Install NUMPY
In [33]: a = np.random.rand (20, 20)
In [34]: res = np.linalg.det (a)
In [35]: Res
Out [35]: 0.09252260373277807

Working hours for the matrix 20×20:

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

Answer 2, Authority 50%

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.

Programmers, Start Your Engines!

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.

Recent questions