《求解线性方程组——超松弛迭代法(c)》由会员分享,可在线阅读,更多相关《求解线性方程组——超松弛迭代法(c)(4页珍藏版)》请在金锄头文库上搜索。
1、求解线性方程组求解线性方程组超松弛迭代法超松弛迭代法#include #include using namespace std;float *one_array_malloc(int n); /一维数组分配float *two_array_malloc(int m,int n); /二维数组分配float matrix_category(float* x,int n);int main()const int MAX=100;/最大迭代次数int n,i,j,k;float* a;float* x_0; /初始向量float* x_k; /迭代向量float precision; /精度floa
2、t w; /松弛因子coutprecision;coutn;a=two_array_malloc(n,n+1);coutaij;x_0=one_array_malloc(n);coutx_0i;x_k=one_array_malloc(n);coutw;float temp;/迭代过程for(k=0;kMAX;k+)for(i=0;in;i+)temp=0;for(j=0;ji;j+)temp=temp+aij*x_kj;x_ki=ain-temp;temp=0;for(j=i+1;jn;j+)temp=temp+aij*x_0j;x_ki=(x_ki-temp)/aii;x_ki=(1-w)
3、*x_0i+w*x_ki;/求两解向量的差的范数for(i=0;in;i+)x_0i=x_ki-x_0i;if(matrix_category(x_0,n)precision)break;elsefor(i=0;in;i+)x_0i=x_ki;/输出过程if(MAX=k)cout“迭代不收敛n“;cout“迭代次数为:“kendl;cout“解向量为:n“;for(i=0;in;i+)cout“x“i“: “x_kiendl;return 0;float *one_array_malloc(int n) /一维数组分配float *a;a=(float *)malloc(sizeof(float)*n);return a;float *two_array_malloc(int m,int n) /二维数组分配float *a;int i;a=(float *)malloc(m*sizeof(float *);for (i=0;im;i+)ai=(float *)malloc(n*sizeof(float);return a;float matrix_category(float* x,int n)int i;float temp=0;for(i=0;in;i+)temp=temp+fabs(xi);return temp;