In [1]:
# input: equation system Ax = b
A = matrix([
[1, 2],
[2, 3],
[3, 4]])
b = vector([1,
2,
0])
#
In [2]:
Apinv = (A.T * A)^-1 * A.T
show(LatexExpr(r"A{T} \cdot A = "), A.T * A)
show(LatexExpr(r"(A{T} \cdot A)^{-1} = "), (A.T * A)^-1)
show(LatexExpr(r"A^{\#} = (A{T} \cdot A)^{-1} \cdot A^{T} = "), Apinv)
In [3]:
x = Apinv * b
show(LatexExpr(r"\bar{x} ="), x)
In [4]:
show(LatexExpr(r"A \cdot \bar{x} ="), A*x)
show(LatexExpr(r"b = "), b)
In [ ]:
In [5]:
U, S, V = matrix(RDF, A).SVD()
show(U,S,V)
In [6]:
Si = matrix(RDF, A.ncols(), A.nrows())
for i in range(S.ncols()):
Si[i,i] = S[i,i]^-1 if S[i,i] != 0 else 0.0
Apinv = V * Si * U.T
show(Apinv)
In [7]:
x = Apinv * b
show(LatexExpr(r"\bar{x} ="), x)
In [8]:
show(LatexExpr(r"A \cdot \bar{x} ="),A*x)
show(LatexExpr(r"b = "), b)
In [ ]:
In [9]:
try:
# try rational field first
Q,R = A.QR()
except TypeError:
# if it doesn't work, use real double field
Q,R = matrix(RDF, A).QR()
show(LatexExpr(r"Q ="), Q)
show(LatexExpr(r"R ="), R)
In [10]:
Xsym = vector([var("x{}".format(i)) for i in range(A.ncols())])
RX = R * Xsym
QTb = Q.T * b
show(LatexExpr(r"R x = "), RX)
show(LatexExpr(r"Q^T b = "),QTb)
In [11]:
sol = solve([RX[i] == QTb[i] for i in range(A.nrows())], *Xsym)
if sol:
for s in sol:
show(s)
else:
print "No solution found"
In [ ]: