Skip to content

Commit

Permalink
feat: Sherman–Morrison formula
Browse files Browse the repository at this point in the history
  • Loading branch information
Tiphereth-A committed Mar 31, 2024
1 parent 42bda6a commit b97352d
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,9 @@ notebook:
- mat_det_rd: 求矩阵的行列式(随机化算法)
code_ext: hpp
test_ext: cpp
- sherman_morrison: Sherman–Morrison 公式
code_ext: hpp
test_ext: cpp
- bitmat: 静态 Bool 矩阵
code_ext: hpp
test_ext: cpp
Expand Down
26 changes: 26 additions & 0 deletions src/code/lalg/sherman_morrison.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#ifndef TIFALIBS_LALG_SHERMAN_MORRISON
#define TIFALIBS_LALG_SHERMAN_MORRISON

#include "../util/util.hpp"

namespace tifa_libs::math {

template <class Mat, class T = typename Mat::value_type>
requires std::same_as<T, typename Mat::value_type>
constexpr void sherman_morrison(Mat &inv_A, vec<T> const &u, vec<T> const &v) {
u32 n = inv_A.row();
assert(n == inv_A.col());
vec<T> x(n), y(n);
for (u32 i = 0; i < n; ++i)
for (u32 j = 0; j < n; ++j)
x[i] += inv_A[i][j] * u[j], y[j] += v[i] * inv_A[i][j];
T sum = 1;
for (u32 i = 0; i < n; ++i)
for (u32 j = 0; j < n; ++j) sum += v[i] * inv_A[i][j] * u[j];
for (u32 i = 0; i < n; ++i)
for (u32 j = 0; j < n; ++j) inv_A[i][j] -= x[i] * y[j] / sum;
}

} // namespace tifa_libs::math

#endif
Empty file.
5 changes: 5 additions & 0 deletions src/doc_tex/lalg/sherman_morrison.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
根据方阵 \(A^{-1}\) 和列向量 \(u,v\) 计算 \((A+uv^T)^{-1}\)

\[
\left(A+uv^T\right)^{-1}=A^{-1}-\frac{A^{-1}uv^TA^{-1}}{1+v^TA^{-1}u}
\]
Empty file.

0 comments on commit b97352d

Please sign in to comment.