Created
June 2, 2014 09:46
-
-
Save armanbilge/3931c69576720133cec4 to your computer and use it in GitHub Desktop.
Transforms the given matrix to reduced row echelon form.
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
#!/usr/bin/env python3 | |
import sys | |
from fractions import Fraction | |
mult = lambda r,f: [f * x for x in r] | |
add = lambda r1,r2: [x + y for x,y in zip(r1,r2)] | |
def print_matrix(m): | |
for r in m: print('\t'.join(str(x) for x in r)) | |
print() | |
m = [] | |
for l in sys.stdin: | |
if l != '\n': m.append(list(map(Fraction.from_float,map(float,l.split())))) | |
print_matrix(m) | |
for i in range(len(m) - 1): | |
for j in range(i+1, len(m)): | |
m[j] = add(m[j], mult(m[i], - m[j][i] / m[i][i])) | |
print_matrix(m) | |
for i in reversed(range(1, len(m))): | |
for j in range(i): | |
m[j] = add(m[j], mult(m[i], - m[j][i] / m[i][i])) | |
print_matrix(m) | |
for i in range(len(m)): | |
m[i] = mult(m[i], 1 / m[i][i]) | |
print_matrix(m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment