Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 6, 2018 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/1e685bfd4629e64b68616001156f4d84 to your computer and use it in GitHub Desktop.
Save komasaru/1e685bfd4629e64b68616001156f4d84 to your computer and use it in GitHub Desktop.
Python script to solve simultaneous equations with Gauss-Jorden method.
#! /usr/local/bin/python3.6
"""
Simultaneous equations solving with Gauss-Jorden method
"""
import sys
import traceback
class GaussJorden:
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):
""" Solving and display """
try:
self.__display_equations()
for k in range(self.n):
p = self.a[k][k]
for j in range(k, self.n + 1):
self.a[k][j] /= p
for i in range(self.n):
if i == k:
continue
d = self.a[i][k]
for j in range(k, self.n + 1):
self.a[i][j] -= d * self.a[k][j]
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 = GaussJorden()
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