Advertisement
dipBRUR

24

Nov 19th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. // Algo: Gaussian Elemination
  2. // Find Solution
  3.  
  4. float a[50][50];
  5. void gaussElimination(int n) {
  6. // Build the forward substitution
  7. for (int i=0; i<n; i++) {
  8. // find the row with largest value
  9. int maxi = i;
  10. for (int j=i+1; j<n; j++) {
  11. if (a[j][i] > a[maxi][i])
  12. maxi = j;
  13. }
  14. // swap the maxRow and i'th row
  15. for (int j=0; j<n+1; j++) // j : indicate column
  16. swap(a[maxi][j], a[i][j]);
  17. // Eliminate the i'th element of the j'th row
  18. for (int j=n; j>=0; j--) {
  19. for (int k=i+1; k<n; k++) {
  20. a[k][j] -= a[k][i] / a[i][i] * a[i][j];
  21. }
  22. }
  23. }
  24. // Do the back substitution
  25. for (int i=n-1; i>=0; i--) {
  26. a[i][n] /= a[i][i];
  27. a[i][i] = 1;
  28. for (int j=i-1; j>=0; j--) {
  29. a[j][n] -= a[j][i] * a[i][n];
  30. a[j][i] = 0;
  31. }
  32. }
  33. // print the result
  34. for (int i=0; i<n; i++)
  35. printf("x%d = %.2f\n", i+1, a[i][n]);
  36. return;
  37. }
  38.  
  39. // Algo: Gaussian Elemination
  40. // Find Determinent
  41.  
  42. double mat[mx][mx];
  43. ll gaussianElimination(int n) {
  44. double pro = 1.0;
  45. int swaps = 0;
  46. for (int i=0; i<n; i++) {
  47. int maxi = i; // find the largest number of remaining column
  48. for (int j=i+1; j<n; j++) {
  49. if (fabs(mat[i][j]) > fabs(mat[i][maxi]))
  50. maxi = j; // column
  51. }
  52. if (fabs(mat[i][maxi]) < EPS) // probably 0
  53. return 0; // it print 'nan'
  54. if (maxi != i) { // need to swap
  55. swaps++;
  56. for (int j=i; j<n; j++)
  57. swap(mat[j][maxi], mat[j][i]);
  58. }
  59. // Eliminate / make 0 in column j
  60. for (int j=i+1; j<n; j++) {
  61. for (int k=n-1; k>=i; k--) {
  62. mat[k][j] -= mat[k][i] / mat[i][i] * mat[i][j];
  63. }
  64. }
  65. // rules : arr[i][j] <- arr[i][j] - (arr[i][1]/arr[1][1]) * arr[1][j]
  66. // for 1st column
  67. pro *= mat[i][i]; // all diagonal's contain's the result
  68. }
  69. if (swaps&1)
  70. pro *= -1;
  71. return pro;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement