Download presentation
Presentation is loading. Please wait.
1
선형 연립 방정식 풀기와 역행렬 구하기 신소재 김경옥
2
Main function void main(){ int sel; sel=0; while(sel==0){ sel=loop();
} return;
3
Loop function (1) int loop(){ variable 설정 /*Menu*/
printf(" \n"); printf("1. Solve the linear systems\n"); printf("2. Inverse matrix\n"); printf("3. End\n"); printf("Enter the program number : "); scanf("%d",&sel); if (sel==3){ return sel; }
4
Loop function (2) /*matirx를 입력받는 부분*/ for(i=0;i<=dim-1;i++){
for(j=0;j<=dim-1;j++){ scanf("%lf",&m[i][j]); com[i][j]=m[i][j];} } /*right side의 상수를 입력받는 부분*/ if (sel==1){ printf("\nInput the %d*1 matrix\n", dim); scanf("%lf",&b[i]); com_b[i]=b[i];} /*inverse matrix의 초기화*/ else{ in[i][i]=1;}
5
Loop function (3) for(i=0;i<dim-1;i++){ test=0; /*normalization*/
/*scaled partial pivoting*/ /*Gaussian elimination*/ }
6
normalization for (j=i;j<=dim-1;j++){ max=0;
for(k=0;k<=dim-1;k++){ if (fabs(max)<fabs(m[j][k])) max=m[j][k]; } for (k=0;k<=dim-1;k++){ m[j][k]=m[j][k]/max; if (sel==2) in[j][k]=in[j][k]/max; if (sel==1) b[j]=b[j]/max;
7
Scaled partial pivoting
for(j=i+1;j<=dim-1;j++){ if (m[j][i]==0){ test=test+1;} if (fabs(m[i][i])<fabs(m[j][i])){ for (k=0;k<=dim-1;k++){ swap(&m[i][k], &m[j][k]); if (sel==2) swap(&in[i][k], &in[j][k]);} if (sel==1) swap(&b[i], &b[j]);} } if (test==(dim-i)){ //모든 열값이 0이면 해를 구할 수 없다고 빠져나옴 check=1; break;
8
Gaussian Elimination for(j=i+1;j<=dim-1;j++){
ratio=-m[j][i]/m[i][i]; if (sel==1) b[j]=b[j]+b[i]*ratio; for(k=0;k<=dim-1;k++){ m[j][k]=m[j][k]+m[i][k]*ratio; if (sel==2) in[j][k]=in[j][k]+in[i][k]*ratio; }
9
Loop function (4) Error 처리 if (check==1){
printf("We can't solve this eqautions\n"); return sel=0; } for (i=0;i<=dim-1;i++){ if ( m[i][i]==0){ if (absol(m[i][i]< )){
10
Loop function (5) 선형 연립 방정식 해 구하기 if (sel==1){
for(i=dim-1;i>=0;i=i-1){ x[i]=b[i]/m[i][i]; for(j=dim-1;j>i;j=j-1){ x[i]=x[i]-x[j]*m[i][j]/m[i][i]; } printf("\n"); for(i=0;i<=dim-1;i++){ printf("x[%d]=%lf\n",i+1,x[i]);
11
Loop function (6) Inverse matrix 구하기 else{ for(i=dim-1;i>0;i=i-1){
for(j=i-1;j>=0;j=j-1){ ratio=-m[j][i]/m[i][i]; m[j][i]=0; for(k=0;k<=dim-1;k++){ in[j][k]=in[j][k]+in[i][k]*ratio;} } for(i=0;i<=dim-1;i++){ for(j=0;j<=dim-1;j++){ in[i][j]=in[i][j]/m[i][i];}
12
Loop function (7) 나온 결과 검산하기 check=0; if (sel==1){
for (i=0;i<=dim-1;i++){ temp=0; for (j=0;j<=dim-1;j++){ temp=temp+com[i][j]*x[j];} if (temp!=com_b[i]){ check=1; break;} } if (sel==2){ for (i=0;i<=dim-1;i++){ temp=0; for (j=0;j<=dim-1;j++){ temp=temp+com[i][j]*in[j][i];} if (temp!=1){ check=1; break;} } if (absol(temp-1))> ){ if (absol((temp-com_b[i])/com_b[i])> ){
13
실행 결과(1)
14
실행 결과(2)
15
double을 float으로 변경 시 double 사용시 float 사용시
Similar presentations