返回介绍

Exercises

发布于 2025-02-25 23:43:52 字数 1826 浏览 0 评论 0 收藏 0

1 . Compute the LU decomposition of the following matrix by hand and using numpy

\[\begin{split}\left(\begin{matrix}1&2&3\\2&-4&6\\3&-9&-3\end{matrix}\right)\end{split}\]

A = np.array([[1,2,3],[2,-4,6],[3,-9,-3]])
print(A)
P, L , U = la.lu(A)
print(P)
print(L)
print(U)
[[ 1  2  3]
 [ 2 -4  6]
 [ 3 -9 -3]]
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]
[[ 1.      0.      0.    ]
 [ 0.3333  1.      0.    ]
 [ 0.6667  0.4     1.    ]]
[[ 3.  -9.  -3. ]
 [ 0.   5.   4. ]
 [ 0.   0.   6.4]]

2 . Compute the Cholesky decomposition of the following matrix by hand and using numpy

\[\begin{split}\left(\begin{matrix}4&2&3\\2&4&5\\3&5&8\end{matrix}\right)\end{split}\]

# Your code here

A=np.array([[4,2,3],[2,4,5],[3,5,8]])
np.linalg.cholesky(A)
array([[ 2.    ,  0.    ,  0.    ],
       [ 1.    ,  1.7321,  0.    ],
       [ 1.5   ,  2.0207,  1.291 ]])

3 . Write a function in Python to solve a system

\[Ax = b\]

using SVD decomposition. Your function should take \(A\) and \(b\) as input and return \(x\).

Your function should include the following:

  • First, check that \(A\) is invertible - return error message if it is not
  • Invert \(A\) using SVD and solve
  • return \(x\)

Test your function for correctness.

# Your code here

def svdsolver(A,b):
    U, s, V = np.linalg.svd(A)
    if np.prod(s) == 0:
       print("Matrix is singular")
    else:
       return np.dot(np.dot((V.T).dot(np.diag(s**(-1))), U.T),b)
A = np.array([[1,1],[1,2]])
b = np.array([3,1])
print(np.linalg.solve(A,b))
print(svdsolver(A,b))
[ 5. -2.]
[ 5. -2.]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文