Created
June 30, 2014 08:36
-
-
Save clckwrkbdgr/a67806d08cb40a20565a to your computer and use it in GitHub Desktop.
Solve linear system in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def minor(a, row, col): | |
result = [] | |
for line in a[:row] + a[row+1:]: | |
result.append(line[:col] + line[col+1:]) | |
return result | |
def determinant(a): | |
if len(a) == 2: | |
return a[0][0] * a[1][1] - a[1][0] * a[0][1] | |
result = 0 | |
sign = 1 | |
for j in range(len(a)): | |
result += sign * a[0][j] * determinant(minor(a, 0, j)) | |
sign = -sign | |
return result | |
def replace_column(a, col, values): | |
result = [] | |
for row, value in zip(a, values): | |
result.append(row[:col] + [value] + row[col+1:]) | |
return result | |
def solve_linear_system(matrix, values): | |
d = determinant(matrix) | |
if d == 0: | |
return None | |
return [determinant(replace_column(matrix, i, values)) / d for i in range(4)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment