""" lsqr v1.1.0 Ver.: OK (c) 01/10 - 12/19 Christos Iosifides This program solves the least squares solution x that minimizes norm |A*x-B| Name: lsqr Version: 1.1.0 Copyright: Ch Iossif @ 2010 Author: Christos Iosifidis Date: 20/01/10 Modified: 05/02/10 11:38, 22/12/2019 13:15 Description: Solves the least squares solution x that minimizes norm |A*x-B| Input : M = 4 N = 2 A = [[ 0.588 -0.809] [-0.768 -0.64 ] [-0.404 0.915] [ 0.898 0.441]] B = [-0.05 0.07 0.06 -0.08] Output : X = [-0.09428331 0.00918387] sigma = 0.013424265794185002 Vx = [[ 0.00704931 -0.0001419 ] [-0.0001419 0.00640821]] Copyright (C) Dec 2009 Ch Iossif This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import numpy as np import math M = int(input("M = ")) N = int(input("N = ")) A = [] for i in range(0, M): A_line = [] for j in range(0, N): A_line.append(float(input())) # adding the element A.append(A_line) # adding the row into A matrix B = [] for i in range(0, M): B.append(float(input())) # adding the element #M=4 #N=2 #A=[ [0.588, -0.809], [-0.768, -0.64], [-0.404, 0.915], [ 0.898, 0.441]] #B=[ -0.05, 0.07, 0.06, -0.08] # Python lists to numpy arrays a=np.asarray(A,dtype=np.float64) b=np.asarray(B,dtype=np.float64) m=a.shape[0] n=a.shape[1] # Input print("Input :") print("\nM = ", m , "N = ", n) print("\nA = ") print(a) print("\nB = ") print(b) # Do the math at=np.transpose(a) ata=np.matmul(at,a) ata_1=np.linalg.inv(ata) atb=np.matmul(at,b) x=np.matmul(ata_1,atb) y=b-np.matmul(a,x) sigma=math.sqrt(np.sum(np.square(y))/(m-n)) vx=np.dot(ata_1,sigma) # Output print("\nOutput :") print("\nX = ") print(x) print("\nsigma = ",sigma) print("\nVx = ") print(vx)