检索 SciPy 中稀疏线性求解器 运行 的迭代次数

Retrieving number of iterations that ran for sparse linear solver in SciPy

如何检索 运行 在 SciPy sparse linear system solvers 中达到指定容差水平的迭代次数?

求解器支持在每次迭代后调用的 callback 关键字参数。所以你可以这样做:

def solve_sparse(A, b):
  num_iters = 0

  def callback(xk):
    num_iters += 1

  # call the solver on your data
  return scipy.sparse.linalg.cg(A, b, callback=callback)[0]

对于Python3,以下作品:

    def solve_sparse(A, b):
      num_iters = 0

      def callback(xk):
         nonlocal num_iters
         num_iters+=1

      x,status=scipy.sparse.linalg.cg(A, b,tol=1e-15, callback=callback)
      return x,status,num_iters

perimosocordiae 对解决“UnboundLocalError”的回答进行了微小的更改:

def solve_sparse(A, b):
    solve_sparse.num_iters = 0

    def callback(xk):
        solve_sparse.num_iters += 1

    # call the solver on your data
    return scipy.sparse.linalg.cg(A, b, callback=callback)[0]