Skip to content

Instantly share code, notes, and snippets.

@boxmein
Last active April 18, 2022 21:39
Show Gist options
  • Save boxmein/7155d9c731d03a2aa9c0 to your computer and use it in GitHub Desktop.
Save boxmein/7155d9c731d03a2aa9c0 to your computer and use it in GitHub Desktop.
Python script to calculate row echelon matrices from non-row echelon matrices (for Gaussian elimination, say)
#!/usr/bin/env python3
# encoding: utf-8
# Row Echelon Calculator
# (for Gaussian Elimination)
# INPUT:
# Matrix of any dimensions in the following form:
# input := { row, "\n" }, ".\n"
# row := { num, " " }
# num := <float>
# (or, to be short, just separate numbers with spaces, use periods (.) for
# decimal separators, press enter for a new matrix row and type a . to stop)
# OUTPUT:
# New matrix in row-echelon form
# Example
# > 3 4.5 2.0e3 -5
# > 1.3 3.4 5.6 29.71
# > 2.5 3.5 4.5 5.5
# > 3.5 2.1 3.4 9.955
# > .
# Outputs:
# 3.00 4.50 2000.00 -5.00
# 0.00 1.45 -861.07 31.88
# 0.00 0.00 -1810.63 15.16
# 0.00 0.00 0.00 49.86
# row_mult :: [a], Multiplier -> [a]
# multiply a list by a number
def row_mult(row, num):
return [x * num for x in row]
# row_sub :: [a], [a] -> [a]
# subtract one row from another
def row_sub(row_left, row_right):
return [a - b for (a, b) in zip(row_left, row_right)]
# row_echelon :: Matrix -> Matrix
# calculate the row echelon form of the matrix
def row_echelon(mtx):
temp_mtx = list(mtx)
def echelonify(rw, col):
for i, row in enumerate(temp_mtx[(col+1):]):
i += 1
if rw[col] == 0: continue
temp_mtx[i+col] = row_sub(row, row_mult(rw, row[col] / rw[col]))
for i in range(len(mtx)):
# print("d: echelonifying row #"+str(i))
active_row = temp_mtx[i]
echelonify(active_row, i)
# flatten out values very close to zero
temp_mtx = [
[(0 if (0.0000000001 > x > -0.0000000001) else x)
for x in row]
for row in temp_mtx
]
return temp_mtx
if __name__=='__main__':
print ("[ Row Echelon Calculator ] ")
print ("Type any number of rows of whitespace-separated floating numbers to \nmake a matrix.")
print ("Type a . to stop entering a matrix.")
mtx = []
# always limit yo' whiles
n_tries = 1000
while n_tries > 0:
n_tries -= 1
try:
inp = input("> ").strip()
except KeyboardInterrupt:
print("interrupted - exiting")
exit(0)
# we're done here, the matrix has been collected
if inp == '.':
break
elif inp == '':
print("empty line - try again!")
continue
try:
row = list(map(float, inp.split()))
mtx.append(row)
except Exception as e:
print("exception while reading this row:" + str(e))
print("try again!")
# print("d: collected all rows! now beginning calculation")
try:
mtx_result = row_echelon(mtx)
# print("d: done calculating! printing output mtx")
# simple matrix printy thing
for row in mtx_result:
print (' '.join(("{0:.2f}".format(x) for x in row)))
# print("d: eof")
except Exception as e:
print("exception while calculating row echelon form: " + str(e))
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment