此例子使用三个变量、三个方程的情况,如需讨论多个的情况,使用vector稍加修改即可。
使用的方程组如下:
每次迭代的值如下:
程序流程图:
程序代码:
/********雅克比迭代法*********
*1.Xi为每一步迭代的初值,X1=0,Yi存放迭代结果
*2.迭代精度e,max|Xi-Yi|,1<=i<=n
*3.最大迭代次数N
*4.输入数据:
*(1)Bi:方程组的值
*(2)Aij:方程组变量系数
*/
#include<iostream>
#include<math.h>
using namespace std;
double sum(double x[4],double a[4][4],int temp)
{
double res(0);
double temp_res=0;//当i=j时,令其为0
for(int j=1;j<4;j++)
{
if(temp==j)
{
res+=temp_res;
//cout<<"res:"<<res<<endl;
}
else
{
res+=a[temp][j]*x[j];
//cout<<"res:"<<res<<endl;
}
}
return res;
}
//the max in an array
double max(double *array)
{
double max_var = array[1];
for(int i=1;i<4;i++)
{
if(max_var<array[i])
{
max_var=array[i];
}
}
//cout<<"max_var:"<<max_var<<endl;
return max_var;
}
void interation(unsigned N,double a[4][4],double *b,double *x,unsigned k,double e)
{
int i=1;
double Y[4]={0,};
for(;i<4;i++)
{
Y[i]=(b[i]-sum(x,a,i))/a[i][i];
//cout<<"Y"<<i<<":"<<Y[i]<<endl;
}
double max_val[4];
for(i=1;i<4;i++)
{
max_val[i]=fabs(x[i]-Y[i]);
}
double the_max=max(max_val);//get the max in the array
cout<<"the max:"<<the_max<<endl;
if(the_max<e)
{
cout<<"---Iterating successfully-----"<<endl;
cout<<"----------------------------"<<endl;
cout<<"The values are as follows:"<<endl;
for(i=1;i<4;i++)
{
cout<<"Y["<<i<<"]:"<<Y[i]<<" ";
}
cout<<endl;
}
else
{
if(k==N)
{
cout<<"--!---Iteration failed---!--"<<endl;
}
else
{
k=k+1;
x=Y;//x array=Y array
interation(N,a,b,x,k,e);
}
}
}
int main()
{
//store coefficients
//double coeff[4][4]={{0,0,0,0},{0,10,-1,-2},{0,-1,10,-2},{0,-1,-1,5}};
double coeff[4][4];
//store equations' value
//double values[4]={0,7.2,8.3,4.2};
double values[4];
double Y[4];//Y[i]
unsigned i,j;
double e;//precision
unsigned N;//iteration times
unsigned k=1;//flag
//先初始化array为0
memset(Y,0,sizeof(Y));
cout<<"---------------Jacobi Interaction----------------"<<endl;
cout<<"----Three equations and three variables X---------"<<endl;
cout<<"Please input equations' coefficients and values:"<<endl;
cout<<"Please input coeffients from first equation to last:"<<endl;
for(i=1;i<4;i++)
{
for(j=1;j<4;j++)
cin>>coeff[i][j];
}
cout<<"---------------------------------------------"<<endl;
cout<<"Please input equations' values:"<<endl;
for(i=1;i<4;i++)
{
cin>>values[i];
}
cout<<"-----------------------------------------------"<<endl;
cout<<"Please input precision e:"<<endl;
cin>>e;
cout<<"----------------------------------------------"<<endl;
cout<<"Please input interation times N:"<<endl;
cin>>N;
cout<<"----Inputting end....--------------------------"<<endl;
//迭代初值为0
double x[4]={0,0,0,0};
interation(N, coeff,values,x, k, e);
cout<<"----------------"<<endl;
cout<<"Hello Boker..2021/5/11/17:00"<<endl;
return 0;
}
运行结果如下: