這篇文章主要介紹了python實(shí)現(xiàn)迭代法求方程組的根過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
有方程組如下:
迭代法求解x,python代碼如下:
import numpy as np import matplotlib.pyplot as plt A = np.array([[8, -3, 2], [4, 11, -1], [6, 3, 12]]) b = np.array([[20, 33, 36]]) # 方法一:消元法求解方程組的解 result = np.linalg.solve(A, b.T) print('Result:\n', result) # 方法二:迭代法求解方程組的解 B = np.array([[0, 3/8, -2/8], [-4/11, 0, 1/11], [-6/12, -3/12, 0]]) f = np.array([[20/8, 33/11, 36/12]]) error = 1.0e-6 steps = 100 xk = np.zeros((3, 1)) # initialize parameter setting errorlist = [] for k in range(steps): xk_1 = xk xk = np.matmul(B, xk) + f.T print('xk:\n', xk) errorlist.append(np.linalg.norm(xk-xk_1)) if errorlist[-1] < error: print('iteration: ', k+1) break # 把誤差畫出來(lái) x_axis = [i for i in range(len(errorlist))] plt.figure() plt.plot(x_axis, errorlist)