#NEWLINE# def qr_solve( ctx , A , b , norm = None , **kwargs ) : #NEWLINE# #INDENT# '\n        Ax = b => x, ||Ax - b||\n\n        Solve a determined or overdetermined linear equations system and\n        calculate the norm of the residual (error).\n        QR decomposition using Householder factorization is applied, which gives very\n        accurate results even for ill-conditioned matrices. qr_solve is twice as\n        efficient.\n        ' #NEWLINE# if ( norm is None ) : #NEWLINE# #INDENT# norm = A . norm #NEWLINE# #UNINDENT# prec = ctx . prec #NEWLINE# try : #NEWLINE# #INDENT# ctx . prec += 10 #NEWLINE# ( A , b ) = ( ctx . matrix ( A , ** kwargs ) . copy ( ) , ctx . matrix ( b , ** kwargs ) . copy ( ) ) #NEWLINE# if ( A . rows < A . cols ) : #NEWLINE# #INDENT# raise ValueError ( 'cannot solve underdetermined system' ) #NEWLINE# #UNINDENT# ( H , p , x , r ) = ctx . householder ( ctx . extend ( A , b ) ) #NEWLINE# res = ctx . norm ( r ) #NEWLINE# if ( res == 0 ) : #NEWLINE# #INDENT# res = ctx . norm ( ctx . residual ( A , x , b ) ) #NEWLINE# #UNINDENT# return ( ctx . matrix ( x , ** kwargs ) , res ) #NEWLINE# #UNINDENT# finally : #NEWLINE# #INDENT# ctx . prec = prec