[Number theory] Gaussian elimination (integer and floating point type)

Source: Internet
Author: User
Tags cmath

Gaussian elimination element method:

Mathematically, the Gaussian elimination method (or the Gaussian elimination method) (English: Gaussian elimination) is an algorithm in linear algebra that can be used to solve a linear equation, to find the rank of a matrix, and to find the inverse matrix of a reversible square. When used in a matrix, the Gaussian elimination method produces a "line ladder". (From Wikipedia)

The following equations are constructed:

A[0][0]*x0 + a[0][1] *x1 + a[0][2]*x2+...........a[0][n-1]*xn-1 = a[0][n]
A[1][0]*x0 + a[1][1] *x1 + a[1][2]*x2+...........a[1][n-1]*xn-1) = A[1][n]
..................................................
..................................................
A[m-1][0]*x0 + a[m-1][1] *x1 + a[m-1][2]*x2+...........a[m-1][n-1]*xn-1 = a[m-1][n]

There are a total of M equations, there are n unknown quantities (x0,x1, ... XN-1), the unknown quantity is the desired, a[0....m-1][n] is a constant.

The key point in some ACM topics is the tectonic equation, which is often used when solving the expectation of probabilities, to find the state recurrence equation in the problem.

Common E[k] Indicates the desired number of steps to reach the target node from the K-node, so the target node p, e[p]=0, is critical.

Constructs the equation group, brings into the template.


Integer Gaussian elimination Template:

Gaussian elimination template #include <iostream> #include <stdio.h> #include <string.h> #include <string> #includ  e <cmath> using namespace std;  const int maxn=105; int Equ,var; There is a equ equation, var variable element.  The number of augmented arrays is equ, 0 to Equ-1, and the number of columns is var + 1, 0 to Var, respectively.  int A[MAXN][MAXN]; int X[MAXN];  Solution set. BOOL FREE_X[MAXN];  Determines whether the variable is indeterminate.  int free_num;      void Debug (void) {int i,j;          for (i=0;i<equ;i++) {for (j=0;j<var+1;j++) {cout<<a[i][j]<< "";      } cout<<endl;  } cout<<endl;      } inline int gcd (int a, int b) {int t;          while (b!=0) {t=b;          B=a%b;      a=t;  } return A;  } inline int LCM (int a, int b) {return a*b/gcd (b); }//Gaussian elimination method to solve the equations (Gauss-jordan elimination).      (-2 means there is a floating-point number solution, but no integer solution, 1 means no solution, 0 means the unique solution, greater than 0 for the infinite solution, and return free arguments) int Gauss (void) {int i,j,k; int max_r;      The row with the highest absolute value for the current column. int col;      The currently processed column.      int TA,TB;      int LCM;int temp;      int free_x_num;      int free_index;      Converted to a stepped array. col=0;      The currently processed column.          for (k=0;k<equ&&col<var;k++,col++) {//enumerates the currently processed rows. The row that finds the largest absolute value of the col column element is exchanged with the K line.          (To reduce the error when dividing) max_r=k;          for (i=k+1;i<equ;i++) {if (ABS (A[i][col]) >abs (A[max_r][col])) max_r=i;              } if (max_r!=k) {//is exchanged with line K.          for (j=k;j<var+1;j++) swap (a[k][j],a[max_r][j]);              } if (a[k][col]==0) {//indicates that the COL column K line below is all 0, then the next column of the current row is processed. k--;          Continue              } for (i=k+1;i<equ;i++) {//enumerates the rows to be deleted.                  if (a[i][col]!=0) {LCM=LCM (ABS (A[i][col]), ABS (A[k][col]));                  Ta=lcm/abs (A[i][col]), Tb=lcm/abs (A[k][col]); if (a[i][col]*a[k][col]<0) TB=-TB;                  The case of a different number is two numbers added. for (j=col;j<var+1;j++) {a[i][j]=a[i][j]*TA-A[K][J]*TB;      }}}}//debug (); 1.      The absence of solution: the presence of degenerate arrays (0, 0, ..., a) such rows (A! = 0).          for (i=k;i<equ;i++) {//For infinite solutions, if you want to determine which ones are free, then the interchange in the elementary row transformation will be affected, then the interchange should be recorded.      if (a[i][col]!=0) return-1; }//2.      The case of Infinity: in the augmented array of Var * (var + 1) (0, 0, ..., 0) Such a line, that is to say, does not form a strict upper triangular array.      and the number of rows that appear is the number of free arguments.          if (K<var) {///First, the free variable has a var-k, that is, the indeterminate variable has at least var-k.              for (i=k-1;i>=0;i--) {//Line I must not be (0, 0, ..., 0) in the case, because such a line is in line K to equ.              Similarly, line I must not be (0, 0, ..., a), A! = 0 case, such a non-solvable. free_x_num=0;              Used to determine the number of indeterminate arguments in the row, if more than 1 are not solved, they are still indeterminate arguments. for (j=0;j<var;j++) {if (A[i][j]!=0&&free_x[j]) free_x_num++,              Free_index = j; } if (free_x_num>1) continue;              The determined variable cannot be solved.     The description is only an indeterminate variable free_index, then the variable can be solved, and the variable is determined.         Temp=a[i][var]; for (j=0;j<var;j++) {if (A[i][j]!=0&&j!=free_index) temp-=a[i][j]              *X[J]; } X[free_index]=temp/a[i][free_index];              To find out the variable element. free_x[free_index]=0;          The variable is deterministic. } return var-k;      There are var-k of free-variable elements. }//3.      The only solution: a strict upper triangular array is formed in the augmented array of Var * (var + 1). Calculate the Xn-1, Xn-2 ...      X0.          for (i=var-1;i>=0;i--) {Temp=a[i][var];          for (j=i+1;j<var;j++) {if (a[i][j]!=0) temp-=a[i][j]*x[j]; } if (temp%a[i][i]!=0) return-2;          Indicates that there is a floating-point number solution, but no integer solution.      X[i]=temp/a[i][i];  } return 0;      } int main (void) {int I, J;          while (scanf ("%d%d", &equ,&var)!=eof) {memset (a,0,sizeof (a));          memset (x,0,sizeof (x)); memset (free_x,1,sizeof (free_x)); At first it's all uncertain. Variable for (i=0;i<equ;i++)//construct augmented matrix             for (j=0;j<var+1;j++) scanf ("%d", &a[i][j]);          Debug ();          Free_num=gauss ();          if (free_num==-1) printf ("No Solution!\n");          else if (free_num==-2) printf ("with floating-point solution, no integer Solution!\n"); else if (free_num>0) {printf ("Infinitely many solutions!")              The number of free arguments is%d\n ", free_num);                  for (i=0;i<var;i++) {if (Free_x[i]) printf ("x%d is indeterminate \ n", i+1);              else printf ("x%d:%d\n", I+1,x[i]);          }} else {for (i=0;i<var;i++) printf ("x%d:%d\n", I+1,x[i]);      } printf ("\ n");  } return 0; }

Floating-point Gaussian elimination Template:

#include <iostream> #include <cstdio> #include <cstring> #include <string.h> #include <cmath > #include <iomanip> #include <algorithm>using namespace std;///floating-point Gaussian elimination template const double Eps=1e-12;const int maxm=1000;///m equations, n variables const int Maxn=1000;int m,n;double a[maxm][maxn+1];///augmented matrix bool free_x[maxn];/// Determines whether an indeterminate variable is a double x[maxn];///solution set int sign (double x) {return (x>eps)-(x<-eps);}    /** return Value: 1 No solution 0 have and only one solution >=1 have multiple solutions, according to Free_x to determine which is the solution */int Gauss () {int i,j;    int row,col,max_r;        m=n;///n an equation, n variables of the kind of case for (row=0,col=0;row<m&&col<n;row++,col++) {max_r=row;                for (i=row+1;i<m;i++)///Find the maximum value in all rows of the current column (reduce the error when doing division) {if (sign (fabs (a[i][col))-fabs (A[max_r][col]) >0)        Max_r=i;        } if (Max_r!=row) {for (j=row;j<n+1;j++) swap (a[max_r][j],a[row][j]);            } if (sign (a[row][col)) ==0)///The current column row line below is all 0 (including row row) {row--;Continue            } for (i=row+1;i<m;i++) {if (A[i][col) ==0) continue;            Double Tmp=a[i][col]/a[row][col];        for (j=col;j<n+1;j++) a[i][j]-=a[row][j]*tmp; }} for (i=row;i<m;i++)///col=n exists 0 ...    0,a case, no solution {if (sign (A[i][col])) return-1; } if (Row<n)//Presence 0 ... 0,0 case, there are multiple solutions, the number of free arguments is N-row {for (i=row-1;i>=0;i--) {int free_num=0;///the number of free arguments in                     T free_index;///free variable sequence number for (j=0;j<n;j++) {if (sign (a[i][j])!=0&&free_x[j])            Free_num++,free_index=j; if (free_num>1) continue;///the number of indeterminate arguments in the row is more than 1 and cannot be solved, they are still indeterminate arguments///Only one indeterminate variable Free_inde            x, the variable can be solved, and the variable is determined by double tmp=a[i][n]; for (j=0;j<n;j++) {if (a[i][j)!=0&&j!=free_index) tmp-=a[i][j     ]*X[J];       } X[free_index]=tmp/a[i][free_index];        Free_x[free_index]=false;    } return N-row;        }///has and only one solution, strict upper triangular matrix (n==m) for (i=n-1;i>=0;i--) {double tmp=a[i][n];                for (j=i+1;j<n;j++) if (sign (a[i][j])!=0) tmp-=a[i][j]*x[j];    X[i]=tmp/a[i][i]; } return 0;}    Template End int T,xx;int main () {cin>>t;        while (t--) {cin>>n>>xx;        memset (A,0,sizeof (a));                for (int i=0;i<n;i++) {if (i==xx) {a[i][i]=1;                a[i][n]=0;            Continue            } a[i][i]=1;            A[i][n]=1;            a[i][(i-1+n)%n]=-0.5;        a[i][(i+1)%n]=-0.5;        } Gauss ();    Cout<<setiosflags (ios::fixed) <<setprecision (4) <<x[0]<<endl; } return 0;}

A topic of integral Gaussian elimination: http://blog.csdn.net/sr_19930829/article/details/38959149

A topic of floating-point Gaussian elimination: Http://blog.csdn.net/sr_19930829/article/details/41551101



[Number theory] Gaussian elimination (integer and floating point type)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.