import numpy as np import matplotlib.pyplot as plt print('------ 3.14 ---------------') print("Droite passant au mieux par 4 points donnés.") points = np.array([[-2, 1], [3, 5], [8, 9], [13, 12]], np.float64) # Données matA = np.array([np.ones(points.shape[0]), points[:,0]]).T vecb = points[:,1] v_sol = np.linalg.lstsq(matA, vecb, rcond=None)[0] # Solution approchée print("matA=\n", matA) print("Solution = ", v_sol) print("matA*v_sol=", np.dot(matA, v_sol)) # Vérification. b = v_sol[0] a = v_sol[1] xx = np.array([-3, 14]) # Abscisses des extrémités de la droite yy = a*xx + b # Ordonnées des extrémités de la droite plt.plot(points[:,0], points[:,1], 'o') # Affiche les points plt.plot(xx, yy, '-') # Trace la droite plt.title('droite passant "au mieux" par les points.') plt.xlabel('x') plt.ylabel('y = a*x + b') plt.text(-2.5, 12, 'a = ' + '{:10.6f}'.format(a), color='black', fontsize=12) plt.text(-2.5, 11, 'b = ' + '{:10.6f}'.format(b), color='black', fontsize=12) plt.axis([-3, 14, 0, 14]) # Limites des axes plt.show()