gaussj.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <math.h>
  2. #define NRANSI
  3. #include "nrutil.h"
  4. //#define REAL float
  5. #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
  6. void gaussj(REAL **a, int n, REAL **b, int m)
  7. {
  8. int *indxc,*indxr,*ipiv;
  9. int i,icol,irow,j,k,l,ll;
  10. REAL big,dum,pivinv,temp;
  11. indxc=ivector(1,n);
  12. indxr=ivector(1,n);
  13. ipiv=ivector(1,n);
  14. for (j=1;j<=n;j++) ipiv[j]=0;
  15. for (i=1;i<=n;i++) {
  16. big=0.0;
  17. for (j=1;j<=n;j++)
  18. if (ipiv[j] != 1)
  19. for (k=1;k<=n;k++) {
  20. if (ipiv[k] == 0) {
  21. if (fabs(a[j][k]) >= big) {
  22. big=fabs(a[j][k]);
  23. irow=j;
  24. icol=k;
  25. }
  26. } else if (ipiv[k] > 1) nrerror("gaussj: Singular Matrix-1");
  27. }
  28. ++(ipiv[icol]);
  29. if (irow != icol) {
  30. for (l=1;l<=n;l++) SWAP(a[irow][l],a[icol][l])
  31. for (l=1;l<=m;l++) SWAP(b[irow][l],b[icol][l])
  32. }
  33. indxr[i]=irow;
  34. indxc[i]=icol;
  35. if (a[icol][icol] == 0.0) nrerror("gaussj: Singular Matrix-2");
  36. pivinv=1.0/a[icol][icol];
  37. a[icol][icol]=1.0;
  38. for (l=1;l<=n;l++) a[icol][l] *= pivinv;
  39. for (l=1;l<=m;l++) b[icol][l] *= pivinv;
  40. for (ll=1;ll<=n;ll++)
  41. if (ll != icol) {
  42. dum=a[ll][icol];
  43. a[ll][icol]=0.0;
  44. for (l=1;l<=n;l++) a[ll][l] -= a[icol][l]*dum;
  45. for (l=1;l<=m;l++) b[ll][l] -= b[icol][l]*dum;
  46. }
  47. }
  48. for (l=n;l>=1;l--) {
  49. if (indxr[l] != indxc[l])
  50. for (k=1;k<=n;k++)
  51. SWAP(a[k][indxr[l]],a[k][indxc[l]]);
  52. }
  53. free_ivector(ipiv,1,n);
  54. free_ivector(indxr,1,n);
  55. free_ivector(indxc,1,n);
  56. }
  57. #undef SWAP
  58. #undef NRANSI