Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 18, 2018 07:04
Show Gist options
  • Save komasaru/e4ce0cc56639557d2ab343bff3666ec1 to your computer and use it in GitHub Desktop.
Save komasaru/e4ce0cc56639557d2ab343bff3666ec1 to your computer and use it in GitHub Desktop.
Python script to solve approximate equation with least squares method.
#! /usr/local/bin/python3.6
"""
Solving approximate equation with least squares method
"""
import sys
import traceback
class LeastSquaresMethod:
N, M = 7, 5 # Number of data, Dimension of curve
X = [-3, -2, -1, 0, 1, 2, 3] # Measurement data x
Y = [ 5, -2, -3, -1, 1, 4, 5] # Measurement data y
def __init__(self):
self.a = [[0.0 for _ in range(self.M + 2)] for _ in range(self.M + 1)]
self.s = [0.0 for _ in range(2 * self.M + 1)]
self.t = [0.0 for _ in range(self.M + 1)]
def exec(self):
""" Executeion """
try:
self.__calc_st()
self.__ins_st()
self.__sweep_out()
self.__display()
except Exception as e:
raise
def __calc_st(self):
""" Calculation of s and t """
try:
for i in range(self.N):
for j in range(2 * self.M + 1):
self.s[j] += (self.X[i] ** j)
for j in range(self.M + 1):
self.t[j] += (self.X[i] ** j) * self.Y[i]
except Exception as e:
raise
def __ins_st(self):
""" Insertion of s and t into a """
try:
for i in range(self.M + 1):
for j in range(self.M + 1):
self.a[i][j] = self.s[i + j]
self.a[i][self.M + 1] = self.t[i]
except Exception as e:
raise
def __sweep_out(self):
""" Sweeping out """
try:
for k in range(self.M + 1):
p = self.a[k][k]
for j in range(k, self.M + 2):
self.a[k][j] /= p
for i in range(self.M + 1):
if i == k:
continue
d = self.a[i][k]
for j in range(k, self.M + 2):
self.a[i][j] -= d * self.a[k][j]
except Exception as e:
raise
def __display(self):
""" Computation of y value and display """
try:
for k in range(self.M + 1):
print("a{:d} = {:10.6f}".format(k, self.a[k][self.M + 1]))
print(" x y")
for px in [0.5 * i for i in range(-6, 7)]:
p = 0
for k in range(self.M + 1):
p += self.a[k][self.M + 1] * (px ** k)
print("{:5.1f}{:5.1f}".format(px, p))
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = LeastSquaresMethod()
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