/* Jacobi Method */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
int it=0;
double **a;
double *b;
double *s;
#define EPS 1e-5 // 최대 오차
#define ITOR 500 // 최대 반복 횟수
int n; // 행렬의 갯수
FILE *fp;
double** matrix_malloc(int n)
{
double **a;
int i,j;
a=(double **)malloc(n*sizeof(double));
for(i=0;i<n;i++)
a[i]=(double *)malloc(n*sizeof(double));
for(i=0;i<n;i++){
for(j=0;j<n;j++){
a[i][j] = 0.0;
}
}
return a;
}
double * b_malloc(int n)
{
double *b;
b = (double*)malloc(n*sizeof(double));
return b;
}
double * s_malloc(int n)
{
double *s;
s = (double*)malloc(n*sizeof(double));
return s;
}
void matrix_free(int n)
{
int i;
for(i=0;i<n;i++)
free(a[i]);
free(a);
}
void b_free()
{
free(b);
}
void s_free()
{
free(s);
}
void Jacobi_Method(void)
{
int i,j;
double a_norm, x_norm, w;
double *x, *x1;
int it =0;
x = s_malloc(n);
x1 = s_malloc(n);
for(i=0;i<n;i++)
x[i] = 0.0;
printf("Iteration");
for(i=0;i<n;i++)
printf(" x%d ",i);
printf("\n");
do{
it++;
for(j=0;j<n;j++)
x1[j]=x[j];
a_norm = 0.0;
x_norm = 0.0;
for(i=0;i<n;i++) {
w = b[i];
for(j=0;j<n;j++)
{
if(j!=i)w -= a[i][j]*x1[j];
}
w /= a[i][i];
a_norm += fabs(x[i]-w);
x_norm += fabs(w);
x[i] = w;
}
printf(" %-2d ",it);
for(i=0;i<n;i++)
printf(" %9.5lf", x[i]);
printf("\n");
if( it > ITOR){
printf("Iteration= %d Check Error!!!!", it);
exit(1);
}
} while(a_norm/x_norm > EPS);
free(x);
free(x1);
}
int main(void)
{
int i, j;
if((fp=fopen("matrix.txt", "r"))==NULL){
printf("File error!!\n");
exit(1);
}
fscanf(fp, "%d", &n);
a = matrix_malloc(n);
b = b_malloc(n);
s = s_malloc(n);
// 파일 입력
for(i=0;i<n;i++){
for(j=0;j<n;j++){
fscanf(fp,"%lf",&a[i][j]);
printf("%.2f ",a[i][j]);
}
fscanf(fp,"%lf",&b[i]);
printf("%.2f \n",b[i]);
}
Jacobi_Method();
matrix_free(n);
b_free();
s_free();
fclose(fp);
return 0;
}