3.1 - 6 迭代法
基本思想
对线性方程组
工程应用中
通法:
- 将
改写为 - 任取初始值,如
,将其带入得到方程组解 - 依次得:
- 即得向量序列
,迭代公式 - 迭代次数较高时,向量序列
有可能收敛至逼近精确解的值(不一定)。
根据
定义1:
对于给定方程组
如果
由于需要研究
Jacobi迭代
通法细节:
将
则原方程
可构造一阶定常迭代法:
Jacobbi迭代:
设
Jacobi迭代法的分量计算公式: 记
Gauss-Seidel迭代法
改进Jacobi迭代法:选取分裂矩阵
分量计算公式:
代码:Jacobi迭代
//
// Created by xa on 2021-03-01.
//
#include <iostream>
#include <vector>
using std::vector;
<vector<double>> A;
vector<double> b;
vector<double> x;
vector<double> next_x;
vector
int size = 0;
void iterate(vector<vector<double>> A_, vector<double> b_);
int main(){
<vector<double>> A_{{10, 3, 1}, {2, -10, 3}, {1, 3, 10}};
vector<double> b_{14, -5, 14};
vector(A_, b_);
iterate}
void iterate(vector<vector<double>> A_, vector<double> b_) {
.assign(A_.begin(), A_.end());
A.assign(b_.begin(), b_.end());
b= A.size();
size
<double> x(size);
vector<double> next_x(size);
vector
int k = 0;
while (true) {
for (int i = 0; i < size; ++i) {
double tmp = b[i];
for (int j = 0; j < size; ++j)
if (j != i) tmp -= A[i][j] * x[j];
[i] = tmp / A[i][i];
next_x}
for (int i = 0; i < size; ++i) {
[i] = next_x[i];
xstd::cout << x[i] << ' ';
}
std::cout << " 第"<< k << "次" << std::endl;
if (k > 100) break;
++k;
}
}
代码:Gauss-Seidel迭代
/***区别***/
//Jacobi
for (int j = 0; j < size; ++j)
if (j != i) tmp -= A[i][j] * x[j];
//Gauss-Seidel
for (int j = 0; j < size; ++j) {
if (j < i) tmp -= A[i][j] * next_x[j];
if (j > i) tmp -= A[i][j] * x[j];
}
//
// Created by xa on 2021-03-01.
//
#include <iostream>
#include <vector>
using std::vector;
<vector<double>> A;
vector<double> b;
vector<double> x;
vector<double> next_x;
vector
int size = 0;
void iterate(vector<vector<double>> A_, vector<double> b_);
int main(){
<vector<double>> A_{{10, 3, 1}, {2, -10, 3}, {1, 3, 10}};
vector<double> b_{14, -5, 14};
vector(A_, b_);
iterate}
void iterate(vector<vector<double>> A_, vector<double> b_) {
.assign(A_.begin(), A_.end());
A.assign(b_.begin(), b_.end());
b= A.size();
size
<double> x(size);
vector<double> next_x(size);
vector
int k = 0;
while (true) {
for (int i = 0; i < size; ++i) {
double tmp = b[i];
for (int j = 0; j < size; ++j) {
if (j < i) tmp -= A[i][j] * next_x[j];
if (j > i) tmp -= A[i][j] * x[j];
}
[i] = tmp / A[i][i];
next_x}
for (int i = 0; i < size; ++i) {
[i] = next_x[i];
xstd::cout << x[i] << ' ';
}
std::cout << " 第"<< k << "次" << std::endl;
if (k > 100) break;
++k;
}
}