生活随笔
收集整理的這篇文章主要介紹了
Jacobi迭代法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們在求解矩陣時,有很多種方法,其中當矩陣是大型稀疏矩陣(矩陣中有大部分元素都為0)時,我們可以用迭代法求解。
其中Jacobi迭代法就是很簡單易懂的一種。
我編寫的C++代碼如下,其中文件matrix.txt內容如下,
第一行的第一個數字表示矩陣的行數或者列數,因為rows==cols
下面的三行表示矩陣本體
最后的一行表示該矩陣和向量(x1,x2,x3) 相乘后的結果
3
8 -3 2
4 11 -1
6 3 12
20 33 36
#include <iostream>
#include <fstream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/photo.hpp>
using namespace std;
using namespace cv;
int main()
{
int rows;
int cols;ifstream file(
"matrix.txt");file >> rows;cols = rows;Mat A(rows, cols, CV_32FC1);A.setTo(
0);
for (
int i =
0; i < rows; i++){
for (
int j =
0; j < cols; j++){file >> A.at<
float>(i, j);}}
Mat B(rows, cols, CV_32FC1);B.setTo(
0);
for (
int i =
0; i < rows; i++){
if (A.at<
float>(i, i) ==
0)
continue;
for (
int j =
0; j < cols; j++){
if (j != i){B.at<
float>(i, j) =
0 - (A.at<
float>(i, j) / A.at<
float>(i, i));}}}
Mat g(rows,
1, CV_32FC1);
for (
int i =
0; i < rows; i++){file >> g.at<
float>(i);g.at<
float>(i) /= A.at<
float>(i, i);}file.close();Mat x(rows,
1, CV_32FC1);x.setTo(
0);Mat x2;x.copyTo(x2);
int iter =
10;
for (
int i =
0; i < iter; i++){x2 = B*x + g;x = x2;}
cout <<
"最終結果為" << endl;
for (
int i =
0; i < rows; i++){
cout <<
"x" << i <<
"=" << x.at<
float>(i) <<
"\t";}
return 0;
}
我在這里只迭代了10次,如果想迭代更多的次數,可以修改iter的值,
正確的答案為(3, 2, 1),我們可以看到當迭代10次的時候,和正確的答案已經很接近了。
方法思想,參考下面博客
參考博客:
https://blog.csdn.net/xiaowei_cqu/article/details/8585703
https://blog.csdn.net/zengxyuyu/article/details/53054880
https://blog.csdn.net/u012991190/article/details/51375506
總結
以上是生活随笔為你收集整理的Jacobi迭代法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。