Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Algo: Gaussian Elemination
- // Find Solution
- float a[50][50];
- void gaussElimination(int n) {
- // Build the forward substitution
- for (int i=0; i<n; i++) {
- // find the row with largest value
- int maxi = i;
- for (int j=i+1; j<n; j++) {
- if (a[j][i] > a[maxi][i])
- maxi = j;
- }
- // swap the maxRow and i'th row
- for (int j=0; j<n+1; j++) // j : indicate column
- swap(a[maxi][j], a[i][j]);
- // Eliminate the i'th element of the j'th row
- for (int j=n; j>=0; j--) {
- for (int k=i+1; k<n; k++) {
- a[k][j] -= a[k][i] / a[i][i] * a[i][j];
- }
- }
- }
- // Do the back substitution
- for (int i=n-1; i>=0; i--) {
- a[i][n] /= a[i][i];
- a[i][i] = 1;
- for (int j=i-1; j>=0; j--) {
- a[j][n] -= a[j][i] * a[i][n];
- a[j][i] = 0;
- }
- }
- // print the result
- for (int i=0; i<n; i++)
- printf("x%d = %.2f\n", i+1, a[i][n]);
- return;
- }
- // Algo: Gaussian Elemination
- // Find Determinent
- double mat[mx][mx];
- ll gaussianElimination(int n) {
- double pro = 1.0;
- int swaps = 0;
- for (int i=0; i<n; i++) {
- int maxi = i; // find the largest number of remaining column
- for (int j=i+1; j<n; j++) {
- if (fabs(mat[i][j]) > fabs(mat[i][maxi]))
- maxi = j; // column
- }
- if (fabs(mat[i][maxi]) < EPS) // probably 0
- return 0; // it print 'nan'
- if (maxi != i) { // need to swap
- swaps++;
- for (int j=i; j<n; j++)
- swap(mat[j][maxi], mat[j][i]);
- }
- // Eliminate / make 0 in column j
- for (int j=i+1; j<n; j++) {
- for (int k=n-1; k>=i; k--) {
- mat[k][j] -= mat[k][i] / mat[i][i] * mat[i][j];
- }
- }
- // rules : arr[i][j] <- arr[i][j] - (arr[i][1]/arr[1][1]) * arr[1][j]
- // for 1st column
- pro *= mat[i][i]; // all diagonal's contain's the result
- }
- if (swaps&1)
- pro *= -1;
- return pro;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement