Skip to content

Instantly share code, notes, and snippets.

@guanidene
Created September 26, 2012 08: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 guanidene/3786823 to your computer and use it in GitHub Desktop.
Save guanidene/3786823 to your computer and use it in GitHub Desktop.
Curve fitting using least square technique (python)
#!/usr/bin/python -u
# -*- coding: utf-8 -*-
"""
Curve fitting using least square technique.
License: BSD
"""
__author__ = 'पुष्पक दगड़े (Pushpak Dagade) <guanidene@gmail.com>'
__date__ = 'Sun Sep 16 13:57:48 2012'
import matplotlib.pyplot as plt
from pylab import lstsq
# given data
X = [1, 2, 3, 4, 5, 6]
fx = [235, 130, 115, 105, 100, 99]
f = lambda x: fx[x - 1]
# solve for parameters using least square technique
A_list = []
B_list = []
for x in X[:-1]:
A_list.append([f(x), 1])
temp = (f(x + 1) - f(x))
B_list.append(temp / abs(temp) * (abs(temp) ** (1.0 / 3)))
sol = lstsq(A_list, B_list)[0]
A = sol[0] ** 3
B = - sol[1] / sol[0]
print '(a,b):', sol
print '(A,B):', A, B
# defined the function since the parameters are now available
def f_curve(x, A, B):
if x == 1:
return 235
else:
return f_curve(x - 1, A, B) + A * ((f_curve(x - 1, A, B) - B) ** 3)
# another set of parameters (obtained using some fitting technique I don't know)
A2 = -1.1177e-5
B2 = 24
print '(A2,B2):', A2, B2
# create plots to compare
plt.plot(X, fx, '*--', label='Exp. Data', markersize=10)
plt.plot(X, [f_curve(x, A, B) for x in X], 'h-', label='Plot woth A, B', markersize=10)
plt.plot(X, [f_curve(x, A2, B2) for x in X], 'D-', markersize=6, label='Plot using A2, B2')
plt.legend()
plt.grid()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment