雅可比迭代法和高斯赛德尔迭代法

刚学 Jacobi算法和Gauss_Siedel算法不久,觉的对以后学习会有帮助,所以记下来,希望感兴趣的朋友共勉!

雅克比迭代
   
     
#include < iostream >
#include
" math.h "
using namespace std;
#define n 3
double a[n][n] = {{ 5 , 2 , 1 },{ - 1 , 4 , 2 },{ 2 , - 3 , 10 }}, x[n] = { - 3 , 2 , 1 }, b[n] = { - 12 , 20 , 3 }, c[n];
int i = 0 ,j,k = 0 ,counter = 15 ;
int main()
{

int k = 0 ,i = 0 ;
double num1,E;
float y[n];
do
{
E
= 0 ;
for (j = 0 ;j < n;j ++ )
{
c[j]
= x[j];
}
num1
= 0 ;
for (j = 0 ;j < n;j ++ )
{
if (j != i)
num1
= num1 + a[i][j] * x[j];
}
for (j = 0 ;j < n;j ++ )
{
c[j]
= x[j];
}

y[i]
= (b[i] - num1) / a[i][i];

if (i < n)
{ i
++ ; }

else
{
for (j = 0 ;j < n;j ++ )
{ x[j]
= y[j]; }

for (j = 0 ;j < n;j ++ )
{
if (E < ( float )fabs(c[j] - y[j])) E = ( float )fabs(c[j] - y[j]);
}
if (k >= 7 )
{ cout
<< " Iterations is " << k + 1 << " , " << " Iterative precision is " ;
printf(
" %.6lf\n " ,E);
for (j = 0 ;j < n;j ++ )
printf(
" x[%d]=%.5lf\t " ,j,x[j]);
cout
<< endl << endl;
}
i
= 0 ;
k
++ ;
if (E < 0.001 ) break ;
}
}
while (k <= counter);
cout
<< " Iterations is " << k << endl;
cout
<< " Iterative terminating condition " ;
printf(
" x[%d]-x[%d]oo<%.6lf\n " ,k,k - 1 ,E);
cout
<< " \t\t---------Solution----------- " << endl;
for (i = 0 ;i < n;i ++ )
{
printf(
" x[%d]=%.5lf\n " ,i,x[i]);
}
}

 

 

高斯-赛德尔迭代法
   
     
#include < iostream >
#include
< math.h >
using namespace std;
int main()

{
double a[ 3 ][ 3 ] = {{ 1 , 2 , - 2 },{ 3 , 1 , - 1 },{ 2 , 4 , 1 }},b[ 3 ] = { 10 , 12 , - 20 };

double x[ 3 ] = { 0 , 0 , 0 },sum1,sum2;

int i,j,k,n = 3 ;

for (k = 0 ;k < 5 ;k ++ )

{
for (i = 0 ;i < n;i ++ )

{ sum1
= 0 ;sum2 = 0 ;

for (j = 0 ;j < i - 1 ;j ++ )

{ sum1
= sum1 + a[i][j] * x[j];

}

for (j = i + 1 ;j < n;j ++ )

{sum2
= sum2 + a[i][j] * x[j];}

x[i]
= (b[i] - sum1 - sum2) / a[i][i];

}

for (i = 0 ;i < n;i ++ )

{ printf(
" x%d=%-15f " ,i + 1 ,x[i]);}

printf(
" \n " );

}

}

 

你可能感兴趣的:(迭代)