求解线性方程组的迭代法
实验目的
(1)熟悉求解线性方程组的迭代方法有关理论和方法。
(2)会编写雅可比迭代法和高斯-塞尔德迭代法。
实验内容
1、用雅可比迭代法解方程组。
2、用高斯-塞尔德迭代法解方程组。
实验步骤、程序设计、实验结果及分析
总结
1、用雅克比迭代法解方程组
1.2 程序设计
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+50;
double x[maxn];
double a[maxn][maxn];
double b[maxn];
double t[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
scanf("%lf",&a[i][j]);
scanf("%lf",&b[i]);
}
memset(x,0,sizeof(x));
memset(t,0,sizeof(t));
for(int c=1;c<=10;c++)
{
for(int i=1;i<=n;i++)
{
t[i]=b[i];
for(int j=1;j<=n;j++)
{
if(j!=i)
{
t[i]-=a[i][j]*x[j];
}
}
t[i]/=a[i][i];
//cout<<t[i]<<endl;
}
//cout<<endl;
for(int i=1;i<=n;i++)
{
x[i]=t[i];
printf("%.8lf \n",x[i]);
}
}
return 0;
}
1.3实验结果:
1.3.2结果分析
k X1 X2 X3 K X1 X2 X3
1 7.200000 8.300000 8.400000 6 10.983375 11.983374 12.980394
2 9.710000 10.70000 11.50000 7 10.994416 11.994416 12.993350
3 10.57000 11.57100 12.48200 8 10.998116 11.998116 12.997767
4 10.85350 10.85340 12.82820 9 10.999364 11.999365 12.999245
5 10.95098 11.95099 12.94138 10 10.999785 11.999785 12.999746
通过上述表格可以看出雅克比迭代法随着不断的迭代不断逼近正解,经过十次以后误差小于〖10〗^(-3)
2、用高斯-塞尔德迭代法解方程组。
2.2程序设计:
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+50;
double x[maxn];
double a[maxn][maxn];
double b[maxn];
double t[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
scanf("%lf",&a[i][j]);
scanf("%lf",&b[i]);
}
memset(x,0,sizeof(x));
memset(t,0,sizeof(t));
for(int c=1;c<=10;c++)
{
for(int i=1;i<=n;i++)
{
t[i]=b[i];
for(int j=1;j<i;j++)
{
t[i]-=a[i][j]*t[j];
}
for(int j=i+1;j<=n;j++)
{
if(j!=i)
{
t[i]-=a[i][j]*x[j];
}
}
t[i]/=a[i][i];
//cout<<t[i]<<endl;
}
//cout<<endl;
cout<<endl;
printf("第%d次迭代结果\n",c);
for(int i=1;i<=n;i++)
{
x[i]=t[i];
printf("x[%d]=%.8lf \n",i,x[i]);
}
}
return 0;
}
2.3实验结果:
2.3.2结果分析
k X1 X2 X3 K X1 X2 X3
0 0 0 0 5 10.9989 11.9947 12.9972
1 7.2000 9.0200 11.6440 6 10.9999 11.9999 13.0000
2 10.4308 11.6719 12.8205 7 / / /
3 10.9313 11.9572 12.9778 8 / / /
4 10.9913 11.9947 12.9972 9 / / /
由表格可知,只需六次迭代,就可以使答案误差小于〖10〗^(-3);
总结:
从1.3.2和2.3.2两张表格中可以看出,用高斯-塞尔德迭代法比雅可比迭代法收敛速度更快。