Created
December 4, 2018 17:04
-
-
Save yongjun823/64e81d7d6b920c02059a6995830a6abd to your computer and use it in GitHub Desktop.
가우스 소거법(Gaussian elimination) Python
This file contains hidden or 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
import numpy as np | |
def get_pivot(arr, reverse=False): | |
if reverse: | |
arr = np.flip(arr, 0)[1:] | |
for item in arr: | |
if item != 0: | |
return item | |
def div_arr(mat, arr, idx, reverse=False): | |
temp = get_pivot(arr, reverse) | |
mat[idx] = arr / temp | |
if __name__ == '__main__': | |
matrix = np.array([[3, -1, 2, 12], | |
[1, 2, 3, 11], | |
[2, -2, -1, 2]], dtype=np.float32) | |
for i in range(len(matrix)): | |
my_arr = matrix[i] | |
div_arr(matrix, my_arr, i) | |
n = get_pivot(my_arr) | |
for idx, target in enumerate(matrix[i + 1:]): | |
m = get_pivot(target) | |
temp_my = my_arr * m / n | |
new_target = target - temp_my | |
matrix[i + idx + 1] = new_target | |
for i in range(len(matrix)): | |
my_idx = len(matrix) - i - 1 | |
my_arr = matrix[my_idx] | |
div_arr(matrix, my_arr, my_idx) | |
n = get_pivot(my_arr) | |
for idx in range(len(matrix) - i - 2, -1, -1): | |
target = matrix[idx] | |
m = get_pivot(target, True) | |
temp_my = my_arr * m / n | |
new_target = target - temp_my | |
matrix[idx] = new_target | |
print(matrix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment