当前位置:   article > 正文

python实现雅克比(Jacobi)迭代法_雅克比迭代求解方程组python

雅克比迭代求解方程组python
  1. import numpy as np
  2. #e为误差
  3. def Jacobi(A,b,x,e,times=100):
  4. length, width = np.shape(A)
  5. D = np.mat(np.diag(np.diag(A)))
  6. L = np.triu(A, 1)
  7. U = np.tril(A, -1)
  8. J = -D.I * (L + U)
  9. H = np.eye(length) - D.I * A
  10. eig,_ = np.linalg.eig(H)
  11. spectral_radius = max(abs(eig))
  12. if spectral_radius < 1:
  13. print('此方程组收敛,谱半径为',round(spectral_radius,5))
  14. x0=x
  15. x = J * x + D.I * b
  16. #x = D.I*(b-(L+U)*x0)
  17. k = 1
  18. while k < times:
  19. if abs(np.max(abs(x-x0), axis=0))>e:
  20. x0=x
  21. x = J * x + D.I * b
  22. #x=D.I*(b-(L+U)*x0)
  23. k += 1
  24. else:
  25. print('当精度为', e, '时,Jacobi在%d次内收敛' % k)
  26. break
  27. print('Jacobi迭代解为\n', x)
  28. B = np.mat([[8,-1,1],[2,10,-1],[1,1,-5]])
  29. b = np.mat('1;4;3')
  30. x = np.mat('0;0;0')
  31. e = 0.001
  32. times = 100
  33. Jacobi(B,b,x,e,times)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/78121
推荐阅读
相关标签
  

闽ICP备14008679号