$search
00001 /* ged.cpp -- Gaussian elimination linear equation solvers. 00002 * 00003 * (C) 2001, C. Bond. All rights reserved. 00004 * 00005 * Simple pivoting on zero diagonal element supported. 00006 * Eliminates unnecessary zeroing of lower triangle. 00007 * Does not scale rows to unity pivot value. 00008 * Swaps b[] as well as a[][], so a pivot ID vector 00009 * is not required. 00010 */ 00011 #include <math.h> 00012 #include "bmtk/matrix.hh" 00013 00014 namespace bmtk { 00015 00016 int gelimd(float **a,float *b,float *x, int n) 00017 { 00018 float tmp,pvt,*t; 00019 int i,j,k,itmp; 00020 00021 for (i=0;i<n;i++) { // outer loop on rows 00022 pvt = a[i][i]; // get pivot value 00023 if (!pvt) { 00024 for (j=i+1;j<n;j++) { 00025 if((pvt = a[j][i]) != 0.0) break; 00026 } 00027 if (!pvt) return 1; // nowhere to run! 00028 t=a[j]; // swap matrix rows... 00029 a[j]=a[i]; 00030 a[i]=t; 00031 tmp=b[j]; // ...and result vector 00032 b[j]=b[i]; 00033 b[i]=tmp; 00034 } 00035 // (virtual) Gaussian elimination of column 00036 for (k=i+1;k<n;k++) { // alt: for (k=n-1;k>i;k--) 00037 tmp = a[k][i]/pvt; 00038 for (j=i+1;j<n;j++) { // alt: for (j=n-1;j>i;j--) 00039 a[k][j] -= tmp*a[i][j]; 00040 } 00041 b[k] -= tmp*b[i]; 00042 } 00043 } 00044 // Do back substitution 00045 for (i=n-1;i>=0;i--) { 00046 x[i]=b[i]; 00047 for (j=n-1;j>i;j--) { 00048 x[i] -= a[i][j]*x[j]; 00049 } 00050 x[i] /= a[i][i]; 00051 } 00052 return 0; 00053 } 00054 00055 /* This version preserves the matrix 'a' and the vector 'b'. */ 00056 int gelimd2(float **a,float *b,float *x, int n) 00057 { 00058 float tmp,pvt,*t,**aa,*bb; 00059 int i,j,k,itmp,retval; 00060 00061 retval = 0; 00062 aa = new float *[n]; 00063 bb = new float [n]; 00064 for (i=0;i<n;i++) { 00065 aa[i] = new float [n]; 00066 bb[i] = b[i]; 00067 for (j=0;j<n;j++) { 00068 aa[i][j] = a[i][j]; 00069 } 00070 } 00071 for (i=0;i<n;i++) { // outer loop on rows 00072 pvt = aa[i][i]; // get pivot value 00073 if (!pvt) { 00074 for (j=i+1;j<n;j++) { 00075 if((pvt = a[j][i]) != 0.0) break; 00076 } 00077 if (!pvt) { 00078 retval = 1; 00079 goto _100; // pull the plug! 00080 } 00081 t=aa[j]; // swap matrix rows... 00082 aa[j]=aa[i]; 00083 aa[i]=t; 00084 tmp=bb[j]; // ...and result vector 00085 bb[j]=bb[i]; 00086 bb[i]=tmp; 00087 } 00088 // (virtual) Gaussian elimination of column 00089 for (k=i+1;k<n;k++) { // alt: for (k=n-1;k>i;k--) 00090 tmp = aa[k][i]/pvt; 00091 for (j=i+1;j<n;j++) { // alt: for (j=n-1;j>i;j--) 00092 aa[k][j] -= tmp*aa[i][j]; 00093 } 00094 bb[k] -= tmp*bb[i]; 00095 } 00096 } 00097 // Do back substitution 00098 for (i=n-1;i>=0;i--) { 00099 x[i]=bb[i]; 00100 for (j=n-1;j>i;j--) { 00101 x[i] -= aa[i][j]*x[j]; 00102 } 00103 x[i] /= aa[i][i]; 00104 } 00105 // Deallocate memory 00106 _100: 00107 for (i=0;i<n;i++) { 00108 delete [] aa[i]; 00109 } 00110 delete [] aa; 00111 delete [] bb; 00112 return retval; 00113 } 00114 00115 } // namespace bmtk