数学问题:
用Gauss_Seidel迭代法求解方程组:
初始迭代向量均设为零向量,二范数误差小于1e-4。
解决代码:
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
#define size 10
void Gauss_Seidel(double A[size][size], double B[size], int n, double x0[size]);
int main()
{
double A[size][size]; double B[size]; double x0[size];
int n;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
for (int i = 0; i < n; i++) {
cin >> B[i];
}
for (int i = 0; i < n; i++) {
x0[i] = 0;
}
Gauss_Seidel(A, B, n, x0);
}
void Gauss_Seidel(double A[size][size], double B[size], int n, double x0[size])
{
double xk[size];
for (int i = 0; i < n; i++) {
xk[i] = 0;
}
double eps = 1e-7;
while (true)
{
for (int i = 0; i < n; i++)
{
double leijia = 0.0;
for (int j = 0; j < n; j++)
{
if (j < i)
{
leijia = leijia + A[i][j] * xk[j];
}
if (j > i)
{
leijia = leijia + A[i][j] * x0[j];
}
}
xk[i] = (1.0 / A[i][i]) * (B[i] - leijia);
}
double Fanshu_max = 0.0;
for (int i = 0; i < n; i++)
{
if (fabs(xk[i] - x0[i]) > Fanshu_max)
{
Fanshu_max = fabs(xk[i] - x0[i]);
}
}
if (Fanshu_max < eps)
{
break;
}
for (int i = 0; i < n; i++)
{
x0[i] = xk[i];
}
}
for (int i = 0; i < n; i++)
{
cout << fixed << setprecision(2) << xk[i] << " ";
}
}
使用方法:
第一行输入方程组阶度:m
第二行至第m+1行输入二维数组A,即线性方程组的系数矩阵(非奇异)
第m+2行输入矩阵B,即常数项列向量
测试输入:
3
8 -3 2
4 11 -1
2 1 4
20 33 12
;
预期输出:
3.00 2.00 1.00
问题解决:
计算结果为:
标签:xk,int,double,Gauss,++,迭代法,x0,Seidel,size From: https://blog.csdn.net/szt12345__/article/details/139204615