
P1: JYS
c04 JWBK378-Fletcher May 23, 2009 4:21 Printer: Yet to come
Basic Mathematical Tools 43
the expected result is x = [2.97142857 20.2 14].
>>> from numpy import *
>>> from numpy.linalg import svd
>>> A = matrix(array(
... [[1.75, 1.5, -2.5],
... [0.0, -0.5, 0.65],
... [0.0, 0.0, 0.25]], float))
>>> A
matrix([[ 1.75, 1.5 , -2.5 ],
[ 0. , -0.5 , 0.65],
[ 0. , 0. , 0.25]])
>>> b = array([0.5, -1.0, 3.5])
>>> b
array([ 0.5, -1. , 3.5])
>>> u, w, v = svd(A)
>>> x = singular
value decomposition back substitution(u, w, v, b)
>>> x = matrix(x).transpose() # column vector
>>> x
matrix([[ 2.97142857],
[ 20.2 ],
[ 14. ]])
"""
if len(u.shape) <>2:
raise RuntimeError, "Expected ’u’ to be a matrix"
if len(w.shape) <>1:
raise RuntimeError, "Expected ’w’ to be a column vector"
if len(v.shape) <>2:
raise RuntimeError, "Expected ’v’ to be a matrix"
if len(b.shape) <>1:
raise RuntimeError, "Expected ’b’ to be a column vector"
m = u.shape[0]
n = u.shape[1]
if w.shape[0] <>n:
raise RuntimeError, "’w’ column vector has incorrect size"
if b.shape[0] <>m:
raise RuntimeError, "’b’ column vector has incorrect size"
if v.shape[0] <> n or v.shape[1] <>n:
raise RuntimeError, "’v’ matrix has incorrect size"
tmp = numpy.zeros(n)
for j in range(n):
s = 0.0
if w[j] <>0:
for i in range(m):
s += u[i, j]*b[i]
s /= w[j]
tmp[j] = s
x = numpy.zeros(n)