Note: the code without pivoting is the same as the one given below except that
/* This is a gaussian elimination program with pivoting. The matrix is directly programmed into this code so that the emphasis is on the mathematics. An operational code would more than likely read in the matrix from a file so that the program would not have to be re-compiled each time a new matrix is used. The matrix given is the one for the circuit problem stated at the beginning of chapter 6. The matrix is in an array called a; which is an n by n+1 array. The choice of pivots is kept in an array called row[]. */ #include#include main() { int n, n1, k, j, j1, l, i, i1, p, trow, row[10]; float a[5][6]={5.,5,0,0,0,5.5,0,0,1,-1,-1,0,0,0,0,2,-3,0,1,-1,-1,0,0,0,0,5,-7,-2,0,0}; float x[10], temp, temp1, mult, sum; n=5; n1=n-1; /*print the matrix */ for(k=0;k<=n1;k++) {for(l=0;l<=n;l++) printf("%e \t",a[k][l]); printf("\n"); } for(i=0;i<=n1;i++) row[i]=i; /*initialize the array row*/ /*This outermost of 3 loops that performs the elimination step */ for(i=0; i<=n1;i++) /* First, find the choice of pivot */ { p=i; n1=n-1; i1=i+1; temp=fabs(a[row[i]][i]); for(j=i1;j temp) {p=j; temp=temp1;} } if(temp<1.E-9) {printf("no solution is likely \n"); return;} /* The largest pivot value is in temp and p is the corresponding index of the array row. If the largest pivot is small (< 10^(-9)), then a message is printed that no solution is likely, or can be trusted*/ /*This step performs a simulated row switch by switching the values of row[i] with row[p] */ trow=row[i]; row[i]=row[p]; row[p]=trow; /* This is the elimination step */ for(j=i1; j<=n1;j++) {j1=j+1; mult=a[row[j]][i]/a[row[i]][i]; for(l=i1;l<=n;l++) {a[row[j]][l]=a[row[j]][l]-mult*a[row[i]][l];} } } /* For a debug check, the gaussian reduced matrix together with the row[] array are printed */ printf("\n"); printf("the gauss reduced matrix is \n"); for(k=0;k<=n1;k++) {for(j=0;j<=n;j++) {if(k>j) printf("%f \t",0.); else printf("%f \t",a[row[k]][j]);} printf("\n"); } for(k=0;k<=n1;k++) printf("%d \t",row[k]); printf("\n"); /* Now initialize the solution array, x[] */ for(k=0;k<=n1;k++) x[k]=0; /* Now perform back substitution to calculate the solutions, x[k]*/ n1=n-1; x[n1]=a[row[n1]][n]/a[row[n1]][n1]; for(i=2;i<=n;i++) {sum=0; for(j=n-i+1;j The answer to the circuit problem is the following current values (in amps) i1=.678505, i2=.421495, i3=.257009, i4=.154206, i5=.102804.
Last updated 10/25/95