Posted By

ozkriff on 05/11/09


Tagged


Versions (?)

iterations


 / Published in: C
 

  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int main(void)
  5. {
  6. float b[4] = { 1.42, -0.57, 0.68, -2.14 },
  7. a[4][4] = {
  8. { 0.24, 0.21, 0.06, -0.34 },
  9. { 0.05, 0, 0.12, 0 },
  10. { 0.35, -0.27, 0, 0 },
  11. { 0.12, -0.43, 0.04, -0.21 }
  12. },
  13. x[4] = {0},
  14. y[4] = {0},
  15. e = 0.001;
  16. int i, j,
  17. step = 0,
  18. repeat = 1;
  19.  
  20. for ( i = 0; i < 4; i++ ) {
  21. for ( j = 0; j < 4; j++ )
  22. printf( "% .4f ", a[i][j] );
  23. puts("");
  24. }
  25.  
  26. for ( i = 0; i < 4; i++ )
  27. x[i] = b[i];
  28.  
  29. while ( repeat ) {
  30. repeat = 0;
  31. step++;
  32. printf( "\nstep %i\n", step );
  33.  
  34. if ( step > 30 )
  35. break;
  36.  
  37. for ( i = 0; i < 4; i++ ) {
  38. y[i] = 0;
  39. for ( j = 0; j < 4; j++ )
  40. y[i] += a[i][j] * x[j];
  41. y[i] += b[i];
  42. }
  43.  
  44. for ( i = 0; i < 4; i++ )
  45. printf( "% .4f\n", y[i] );
  46.  
  47. for ( i = 0; i < 4; i++ )
  48. if ( fabs(y[i]-x[i]) >= e )
  49. repeat = 1;
  50.  
  51. for ( i = 0; i < 4; i++ )
  52. x[i] = y[i];
  53. }
  54.  
  55. puts( "answer:" );
  56. for ( i = 0; i < 4; i++ )
  57. printf( "% .4f\n", y[i] );
  58.  
  59. return 0;
  60. }

Report this snippet  

You need to login to post a comment.