我正在尝试编写一个程序来求解带有3个变量x,y,z的线性方程。我知道使用Cramer规则更容易,尤其是因为我知道必要的行列式(我也被困在nxn矩阵中进行泛化),但是我想知道如何使用Jacobi的Method和Gauss-Seidel(再一次,我无法概括它们。所以这是我的方法:
#include <stdio.h>
double jacobi(int k, double x, double y, double z)
{
/*
Solve with Jacobi and Gauss-Seidel (first three iterations)
[2 2 3] [x] [3]
[-1 -3 0]*[y]=[2]
[1 2 1] [z] [0]
initial values x=0, y-0, z=0
*/
double xj, yj, zj;
if(k==1)
{
xj=-3.0*y-2.0;
return xj;
}
else if(k==2)
{
yj=(3.0-2.0*y-2.0*x)/2.0;
return yj;
}
else if(k==3)
{
zj=-2.0*y-x;
return zj;
}
}
double gaseid(int k, double x, double y, double z)
{
double xgs, ygs, zgs;
if(k==1)
{
xgs=-3.0*y-2.0;
return xgs;
}
else if(k==2)
{
ygs=(3.0-2.0*y-2.0*x)/2.0;
return ygs;
}
else if(k==3)
{
zgs=-2.0*y-x;
return zgs;
}
}
int main()
{
FILE *fp;
fp=fopen("Jacobi-Gauss-Siedel.2.txt", "w");
double x=0.0, y=0.0, z=0.0, xj, yj, zj, xgs, ygs, zgs;
int i;
for(i=0; i<3; i++)
{
xj=jacobi(1,x,y,z);
yj=jacobi(2,x,y,z);
zj=jacobi(3,x,y,z);
x=xj, y=yj, z=zj;
fprintf(fp, "xj= %lf \tyj=%lf \tzj=%lf\n", x, y, z);
}
for(i=0; i<3; i++)
{
xgs=jacobi(1,x,y,z);
ygs=jacobi(2,xgs,y,z);
zgs=jacobi(3,xgs,ygs,z);
fprintf(fp, "xgs= %lf \tyj=%lf \tzj=%lf\n", xgs, ygs, zgs);
}
fclose(fp);
return 0;
}
任何人都可以帮助我纠正此程序或为我指明正确的方向,并提供有关如何更好地理解这两种方法的提示吗? 谢谢!