gpt4 book ai didi

c++ - jacobi 迭代方法在 C++ 中有错误的答案

转载 作者:行者123 更新时间:2023-11-28 04:39:54 24 4
gpt4 key购买 nike

我正在编写 Jacobi 迭代法来求解任何线性方程组。该程序适用于某些示例,但不适用于其他示例。例如对于

A=     and B=
7 3 5
2 3 4

这会起作用并且答案是正确的,但是对于

A=     and B=
1 2 3
3 4 7

答案是错误的,而且数字很大。我真的不知道我应该怎么做才能做出正确的计算。我使用了一些其他代码,但我仍然遇到代码问题。

#include <iostream>
using namespace std;

int main(){
double A[10][10], alpha[10][10], B[10], betha[10], x[10][100], sum[10];
int i, j, n, k, kmax;
cout << "insert number of equations \n";
cin >> n;
cout << "insert LHS of equations (a11,a12,...,ann)\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cin >> A[i][j];
}
}
cout << "A=\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cout << A[i][j] << "\t\t";
}
cout << "\n\n";
}
cout << "alpha=\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
if (i == j){
alpha[i][j] = 0;
}
else{
alpha[i][j] = -A[i][j] / A[i][i];
}
}
}
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cout << alpha[i][j] << "\t\t";
}
cout << "\n\n";
}
cout << "insert RHS of equations";
for (i = 1; i <= n; i++){
cin >> B[i];
}
cout << "\nbetha=\n";
for (i = 1; i <= n; i++){
betha[i] = B[i] / A[i][i];
cout << betha[i] << endl;
}
cout << "Enter the number of repetitions." << endl;
cin >> kmax;
k = 0;
for (i = 1; i <= n; i++){
sum[i] = 0;
x[i][k] = betha[i]; //initial values
}
for (k = 0; k <= kmax; k++){
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
sum[i] += alpha[i][j] * x[j][k];
}
x[i][k] = betha[i] + sum[i];
sum[i] = 0;
}
}
cout << "answers:\n\n";
for (i = 1; i <= n; i++){
cout << x[i][kmax] << endl;
}
return 0;
}

最佳答案

您应该再次检查收敛条件。在那里你会发现通常该方法只收敛对角占优矩阵。第一个示例满足该条件,而第二个示例明显违反了该条件。

如果不能保证收敛,可能会出现发散,正如您发现的那样。


更具体地说,第二个例子中的雅可比迭代计算

xnew[0] = (3 - 2*x[1])/1;
xnew[1] = (7 - 3*x[0])/4;

经过两次迭代,步骤的组合给出

xtwo[0] = (3 - 2*xnew[1])/1 = -0.5 + 1.5*x[0];
xtwo[1] = (7 - 3*xnew[0])/4 = -0.5 + 1.5*x[1];

这显然是在用因子 1.5 扩展初始误差。

关于c++ - jacobi 迭代方法在 C++ 中有错误的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com