Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 9, 2018 02:38
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/fcaf3d93acb0c304975cf25c0408656d to your computer and use it in GitHub Desktop.
Save komasaru/fcaf3d93acb0c304975cf25c0408656d to your computer and use it in GitHub Desktop.
Python script to solve simultaneous equations with Gauss-Jorden(pivot) method.
#! /usr/local/bin/python3.6
"""
Simultaneous equations solving with Gauss-Jorden(pivot) method
"""
import math
import sys
import traceback
class GaussJordenPivot:
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):
mx, s = 0, k
for j in range(k, self.n):
if math.fabs(self.a[j][k]) <= mx:
continue
mx = math.fabs(self.a[j][k])
s = j
if mx == 0:
print("解けない!")
sys.exit(0)
for j in range(self.n + 1):
dummy = self.a[k][j]
self.a[k][j] = self.a[s][j]
self.a[s][j] = dummy
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 = GaussJordenPivot()
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