Write a Python function that uses the Jacobi method to solve a system of linear equations given by Ax = b. The function should iterate n times, rounding each intermediate solution to four decimal places, and return the approximate solution x.

Example:

  • Input:A = [[5, -2, 3], [-3, 9, 1], [2, -1, -7]], b = [-1, 2, 3], n=2
  • Output:[0.146, 0.2032, -0.5175]

这道题是使用Jacobi方法解线性方程。

可以简单地得出这样的公式,但是公式的右边是有x的,而这些值是不知道的。

这个Jacobi方法就是先猜一个值,代进去计算。得到一个估计值,再拿估计值代入进行迭代。直到收敛或者是达到指定的次数。这样就可以得到方程组的解。

那么搞清楚了,代码也就比较简单了:

import numpy as np  
def solve_jacobi(A: np.ndarray, b: np.ndarray, n: int) -> list:  
 da = np.diag(A)  
 nda = A - np.diag(da)  
 x = np.zeros(len(b))  
 x_hold = np.zeros(len(b))  
 for _ in range(n):  
  for i in range(len(b)):  
   x_hold[i] = 1/da[i] * (b[i] - sum(nda[i] * x))  
  x = x_hold.copy()  
 return np.round(x, 4).tolist()