def solve(A,b,rtol=10**-8):
'''
Solve the matrix equation A*x=b by QR decomposition.
Parameters
----------
A : 2d ndarray
The coefficient matrix.
b : 1d ndarray
The ordinate values.
rtol : np.float64
The relative tolerance of the solution.
Returns
-------
1d ndarray
The solution.
Raises
------
LinAlgError
When no solution exists.
'''
assert A.ndim==2
nrow,ncol=A.shape
if nrow>=ncol:
result=np.zeros(ncol,dtype=np.find_common_type([],[A.dtype,b.dtype]))
q,r=sl.qr(A,mode='economic',check_finite=False)
temp=q.T.dot(b)
for i,ri in enumerate(r[::-1]):
result[-1-i]=(temp[-1-i]-ri[ncol-i:].dot(result[ncol-i:]))/ri[-1-i]
else:
temp=np.zeros(nrow,dtype=np.find_common_type([],[A.dtype,b.dtype]))
q,r=sl.qr(dagger(A),mode='economic',check_finite=False)
for i,ri in enumerate(dagger(r)):
temp[i]=(b[i]-ri[:i].dot(temp[:i]))/ri[i]
result=q.dot(temp)
if not np.allclose(A.dot(result),b,rtol=rtol):
raise sl.LinAlgError('solve error: no solution.')
return result
评论列表
文章目录