Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 12, 2018 05:25
Show Gist options
  • Save komasaru/53c0c94423e9f83922e583ac03d30618 to your computer and use it in GitHub Desktop.
Save komasaru/53c0c94423e9f83922e583ac03d30618 to your computer and use it in GitHub Desktop.
Python script to solve simultaneous equations with Gauss elimination method.
#! /usr/local/bin/python3.6
"""
Simultaneous equations solving with Gauss elimination method
"""
import sys
import traceback
class GaussElimination:
def __init__(self):
self.a = [
#[ 2, -3, 1, 5],
#[ 1, 1, -1, 2],
#[ 3, 5, -7, 0]
[ 1, -2, 3, -4, 5],
[-2, 5, 8, -3, 9],
[ 5, 4, 7, 1, -1],
[ 9, 7, 3, 5, 4]
]
self.n = len(self.a)
def exec(self):
""" Execution """
try:
self.__display_equations()
for k in range(self.n - 1):
for i in range(k + 1, self.n):
d = self.a[i][k] / self.a[k][k]
for j in range(k + 1, self.n + 1):
self.a[i][j] -= self.a[k][j] * d
for i in range(self.n - 1, -1, -1):
d = self.a[i][self.n]
for j in range(i + 1, self.n):
d -= self.a[i][j] * self.a[j][self.n]
self.a[i][self.n] = d / self.a[i][i]
self.__display_answers()
except Exception as e:
raise
def __display_equations(self):
""" Display of source equations """
try:
for i in range(self.n):
for j in range(self.n):
print("{:+d}x{:d} ".format(self.a[i][j], j + 1), end="")
print("= {:+d}".format(self.a[i][self.n]))
except Exception as e:
raise
def __display_answers(self):
""" Display of answer """
try:
for k in range(self.n):
print("x{:d} = {:f}".format(k + 1, self.a[k][self.n]))
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = GaussElimination()
obj.exec()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment