高斯赛德尔迭代法
我們在求解矩陣時,有很多種方法,其中當(dāng)矩陣是大型稀疏矩陣(矩陣中有大部分元素都為0)時,我們可以用迭代法求解。
關(guān)于該方法的思想和定義,請參考如下博客:
http://www.doc88.com/p-6953977164202.html
我編寫的C++代碼,也是根據(jù)上面的博客中的數(shù)學(xué)公式。
在這里我們使用的數(shù)據(jù)文件matrix.txt為
- 第一行表示矩陣的行數(shù)或者列數(shù)
- 接下來的三行,表示矩陣本體 A
- 最后一行表示 b,A*x=b
- 我們要計算的就是x
代碼如下:
#include <iostream> #include <fstream> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/photo.hpp>using namespace std; using namespace cv;int main() {ifstream file("matrix.txt");int rows;int cols;file >> rows;cols = rows;Mat A(rows, cols, CV_32FC1);/*我們假設(shè)輸入的矩陣對角線元素不為0*/for (int i = 0; i < rows; i++){for (int j = 0; j < cols; j++){file >> A.at<float>(i, j);}}Mat b(1, cols, CV_32FC1);for (int i = 0; i < cols; i++){file >> b.at<float>(i);}file.close();//迭代次數(shù) iter = 10次Mat x(1, cols, CV_32FC1);x.setTo(0);for (int iter = 0; iter < 10; iter++){for (int i = 0; i < rows; i++){float sum = 0;for (int j = 0; j < cols; j++){if (i == j)continue;sum += A.at<float>(i, j)*x.at<float>(j);}x.at<float>(i) = (b.at<float>(i) -sum) / A.at<float>(i, i);}}cout << "最終的結(jié)果為:" << endl;for (int i = 0; i < cols; i++){cout << "x" << i << "=" << x.at<float>(i) << "\t";}return 0; }最后輸出的結(jié)果為
最終結(jié)果為 x0=3 x1=2 x2=1和正確的結(jié)果一樣。在這里我們迭代了10次,求出了最終的結(jié)果。關(guān)于數(shù)值分析,我并沒有投入太多的精力,如果有問題和值得改進(jìn)的地方,希望各位留言。
總結(jié)
- 上一篇: 统计学基本知识三
- 下一篇: MSE和Cross-entropy梯度更