import numpy as np import matplotlib.pyplot as plt def leastSquares(x, y, deg=1): '''Compute the coefficients of a polynomial of degree deg that approximate the dependence y = y(x) by using the Least Squares method. Input: x is an array of values of independent variable; y is an array of measured values of dependent variable y=y(x); deg is the degree of the approximating polynomial. Return: the coefficients of the approximating polynomial in descending order.''' m = len(x) assert len(y) == m a = np.vander(x, deg + 1) pinv_a = np.linalg.pinv(a) w = pinv_a.dot(y) return w def showLeastSquares(x, y, deg=1): fig = plt.figure() fig.set_size_inches(10/2.54, 10/2.54) fig.set_dpi(100) ax = fig.add_subplot(1, 1, 1) ax.set_aspect(1.) xmin = -5 xmax = 5 ax.set_xlim(xmin, xmax) ax.set_ylim(xmin, xmax) ax.grid() ax.axhline(0, color="black") ax.axvline(0, color="black") ax.plot(x, y, "ro") w = leastSquares(x, y, deg) n = 100; dx = (xmax - xmin)/n xx = [ xmin + i*dx for i in range(n+1) ] yy = np.polyval(w, xx) ax.plot(xx, yy) plt.show()