def matrix_powers(m): """Generates infinite sequence of matrix powers, starting from m^0""" yield eye(len(m)) # m^0 yield m # m^1 m_i = mmul(m, m) while True: yield m_i m_i = mmul(m_i, m)
def matrix_powers(m): """Generates infinite sequence of matrix powers, starting from m^0""" yield eye(len(m)) # m^0 yield m # m^1 m_i = mmul( m, m ) while True: yield m_i m_i = mmul( m_i, m )
def ltri_inverse(M, context=FloatContext): """Inverse of the left-triangular matrix""" R = eye(len(M), context=context) for i in xrange(len(M)): m_ii = M[i][i] #diagonal element r_i = R[i] #normalize r_i[:i + 1] = (x / m_ii for x in r_i[:i + 1]) #now subtract it from other rows for j in xrange(i + 1, len(M)): r_j = R[j] m_ji = M[j][i] r_j[:i + 1] = (x - m_ji * y for x, y in izip(r_j[:i + 1], r_i[:i + 1])) return R
def ltri_inverse( M, context=FloatContext): """Inverse of the left-triangular matrix""" R = eye(len(M),context=context) for i in xrange(len(M)): m_ii = M[i][i] #diagonal element r_i = R[i] #normalize r_i[:i+1] = ( x / m_ii for x in r_i[:i+1]) #now subtract it from other rows for j in xrange(i+1,len(M)): r_j = R[j] m_ji = M[j][i] r_j[:i+1] = ( x - m_ji * y for x,y in izip( r_j[:i+1], r_i[:i+1] ) ) return R
def qrl_givens(M, eps=1e-14, context=FloatContext, inverse_q=False): """QR decomposition of a rectangular matrix. R is right-triangular""" n, m = shape_mat(M) R = copy_mat(M) #will be used for inplace computations Q = eye(n, context=context) for j in xrange(min(n, m) - 1, 0, -1): #from last column to the first for i in xrange(j): k_sin = R[i][j] k_cos = R[i + 1][j] k2 = k_sin**2 + k_cos**2 if k2 < eps: continue k = context.sqrt(k2) s = k_sin / k c = k_cos / k givens_inplace(Q, i, i + 1, -s, c) givens_inplace(R, i, i + 1, -s, c) if inverse_q: return Q, R else: return transpose(Q), R
def qrl_givens(M, eps=1e-14, context=FloatContext, inverse_q=False ): """QR decomposition of a rectangular matrix. R is right-triangular""" n,m = shape_mat(M) R = copy_mat(M) #will be used for inplace computations Q = eye( n, context=context ) for j in xrange(min(n,m)-1,0,-1): #from last column to the first for i in xrange(j): k_sin = R[i ][j] k_cos = R[i+1][j] k2 = k_sin**2 + k_cos**2 if k2 < eps: continue k = context.sqrt(k2) s = k_sin / k c = k_cos / k givens_inplace( Q, i, i+1, -s, c ) givens_inplace( R, i, i+1, -s, c ) if inverse_q: return Q,R else: return transpose(Q), R