import numpy as np import matplotlib.pyplot as plt print('------ 3.18 ---------------') print("Approximation d'une fonction paire par une somme de cosinus.") ax = np.linspace(-np.pi, np.pi, 35, np.float64) # Donnée ay = np.exp(-5 * ax**2) # Donnée nbCoef = 15 # Création de la matrice matA = np.zeros((ax.shape[0], nbCoef), np.float64) matA[:, 0] = np.ones(ax.shape[0]) # Première colonne de la matrice # Remplissage des autres colonnes de la matrice for jj in range(1, nbCoef): matA[:, jj] = np.cos(jj * ax) print("Taille de la matrice =", matA.shape) #print("A=\n", matA) # Pour info. # Détermination des coefficients coefs = np.linalg.lstsq(matA, ay, rcond=None)[0] # Coefficients print("Solution = ", coefs) # Graphique, les points, la fonction et son approximation. xx = np.linspace(-np.pi, np.pi, 81,endpoint=True) # Abscisses des points pour tracer les fonctions yy = coefs[0] for jj in range(1, nbCoef): yy += coefs[jj] * np.cos(jj*xx) plt.plot(ax, ay, 'o') # Affiche les points plt.plot(xx, yy, '-') # Trace l'approximation plt.plot(xx, np.exp(-5 * xx**2), '-') # Trace la courbe à approximer plt.title('Approximation de : y = exp(-5 * x**2).') plt.xlabel('x [rad]') plt.ylabel('y = approx. et courbe') plt.legend(['points', 'y=approx(x)', 'y=exp(-5 * x**2)'], loc='upper left') plt.axis([-3.5, 3.5, -0.1, 1.1]) # Limites des axes plt.show() ydiff = yy - np.exp(-5 * xx**2) plt.plot(xx, ydiff, '-') # Trace la différence entrel la fonction et son approximation plt.title('Approximation - fonction') plt.xlabel('x [rad]') plt.ylabel('y = différence') plt.xlim(-3.5, 3.5) # Limites de l'axe X c.f. https://python.developpez.com/tutoriels/graphique-2d/matplotlib/#LII-D fig = plt.gcf(); fig.set_size_inches(8, 5) # autre manière de faire plt.show()