#! /usr/bin/env python # def lstsq_solve_test ( ): #*****************************************************************************80 # ## LSTSQ_SOLVE_TEST tests the NUMPY LINALG LSTSQ operator. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 29 August 2016 # # Author: # # John Burkardt # import numpy as np import platform from r8vec_norm import r8vec_norm from test_ls import p00_a from test_ls import p00_b from test_ls import p00_m from test_ls import p00_n from test_ls import p00_prob_num from test_ls import p00_x print ( '' ) print ( 'LSTSQ_SOLVE_TEST' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' NUMPY LINALG\'s LSTSQ function x=np.linalg.lstsq(A,b)\n' ) print ( ' solves a linear system A*x = b in the least squares sense.' ) print ( ' Compare a tabulated solution X1 to the LSTSQ result X2.' ) prob_num = p00_prob_num ( ) print ( '' ) print ( ' Number of problems = %d' % ( prob_num ) ) print ( '' ) print ( ' Index M N ||B|| ||X1 - X2||' ), print ( ' ||X1|| ||X2|| ||R1|| ||R2||' ) print ( '' ) for prob in range ( 1, prob_num + 1 ): # # Get problem size. # m = p00_m ( prob ) n = p00_n ( prob ) # # Retrieve problem data. # a = p00_a ( prob, m, n ) b = p00_b ( prob, m ) x1 = p00_x ( prob, n ) b_norm = r8vec_norm ( m, b ) x1_norm = r8vec_norm ( n, x1 ) r1 = np.dot ( a, x1 ) - b r1_norm = r8vec_norm ( m, r1 ) # # Use NUMPY's LINALG.LSTSQ on the problem. # x2, r, rank, s = np.linalg.lstsq ( a, b, rcond = None ) x2_norm = r8vec_norm ( n, x2 ) r2 = np.dot ( a, x2 ) - b r2_norm = r8vec_norm ( m, r2 ) # # Compare tabulated and computed solutions. # x_diff_norm = r8vec_norm ( n, x1 - x2 ) # # Report results for this problem. # print ( ' %5d %4d %4d' % ( prob, m, n ), end = '' ) print ( ' %12.4g %12.4g' % ( b_norm, x_diff_norm ), end = '' ) print ( ' %12.4g %12.4g' % ( x1_norm, x2_norm ), end = '' ) print ( ' %12.4g %12.4g' % ( r1_norm, r2_norm ), end = '' ) print ( '' ) # # Terminate. # print ( '' ) print ( 'LSTSQ_SOLVE_TEST' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) lstsq_solve_test ( ) timestamp ( )