.. _chap-fitting: ********* Fitting ********* Here are some exercises to do together: we put these equations into sympy to do curve fitting. We can precede this with a discussion of fitting and how that gives us a system of linear equations. Fitting a straight line ======================= .. math:: m x_1 + b = y_1 \\ m x_2 + b = y_2 which is equivalent to: .. math:: m x_1 + b - y_1 = 0 \\ m x_2 + b - y_2 = 0 :: from sympy import * init_printing(use_unicode=True) m, b = symbols('m b') x1, x2, y1, y2 = symbols('x1 x2 y1 y2') solve([m*x1 + b - y1, m*x2 + b - y2], m, b) # HIT ENTER HERE - there will be a long result :: # now specialize it to specific points x1 = 1 y1 = 7 x2 = 2 y2 = 3 solve([m*x1 + b - y1, m*x2 + b - y2], m, b) result: {b: 11, m: -3} Fitting a parabola ================== .. math:: a {x_1}^2 + b x_1 + c = y_1 \\ a {x_2}^2 + b x_2 + c = y_2 \\ a {x_3}^2 + b x_3 + c = y_3 which is equivalent to: .. math:: a {x_1}^2 + b x_1 + c - y_1 = 0\\ a {x_2}^2 + b x_2 + c - y_2 = 0 \\ a {x_3}^2 + b x_3 + c - y_3 = 0 :: from sympy import * init_printing(use_unicode=True) a, b, c = symbols('a b c') x1, x2, x3, y1, y2, y3 = symbols('x1 x2 x3 y1 y2 y3') solve([a*x1**2 + b*x1 + c - y1, a*x2**2 + b*x2 + c - y2, a*x3**2 + b*x3 + c - y3], a, b, c) # HIT ENTER HERE - there will be a long result :: # now specialize it to specific points x1 = 1 y1 = 1 x2 = 2 y2 = 2 x3 = 3 y3 = 7 solve([a*x1**2 + b*x1 + c - y1, a*x2**2 + b*x2 + c - y2, a*x3**2 + b*x3 + c - y3], a, b, c) result: {a: 2, b: -5, c: 4} Fitting a cubic =============== .. math:: a {x_1}^3 + b {x_1}^2 + c x_1 + d = y_1 \\ a {x_2}^3 + b {x_2}^2 + c x_2 + d = y_2 \\ a {x_3}^3 + b {x_3}^2 + c x_3 + d = y_3 \\ a {x_4}^3 + b {x_4}^2 + c x_4 + d = y_4 which is equivalent to: .. math:: a {x_1}^3 + b {x_1}^2 + c x_1 + d - y_1 = 0\\ a {x_2}^3 + b {x_2}^2 + c x_2 + d - y_2 = 0 \\ a {x_3}^3 + b {x_3}^2 + c x_3 + d - y_3 = 0 \\ a {x_4}^3 + b {x_4}^2 + c x_4 + d - y_4 = 0 :: from sympy import * init_printing(use_unicode=True) a, b, c, d = symbols('a b c d') x1, x2, x3, x4, y1, y2, y3, y4 = symbols('x1 x2 x3 x4 y1 y2 y3 y4') solve([a*x1**3 + b*x1**2 + c*x1 + d - y1, a*x2**3 + b*x2**2 + c*x2 + d - y2, a*x3**3 + b*x3**2 + c*x3 + d - y3, a*x4**3 + b*x4**2 + c*x4 + d - y4], a, b, c, d) # long result x1 = -4 y1 = -3 x2 = -2 y2 = 0 x3 = 2 y3 = 0 x4 = 4 y4 = 2 solve([a*x1**3 + b*x1**2 + c*x1 + d - y1, a*x2**3 + b*x2**2 + c*x2 + d - y2, a*x3**3 + b*x3**2 + c*x3 + d - y3, a*x4**3 + b*x4**2 + c*x4 + d - y4], a, b, c, d)