Guest User

matrix_inverse

a guest
Jan 5th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Globalization;
  4. namespace MatrixInverse
  5. {
  6. class MatrixInverse
  7. {
  8. public static void Main()
  9. {
  10. char esc;
  11. string str,path;
  12. int i,j,n;
  13. double[,] A;
  14. double d;
  15. NumberFormatInfo nfi = new NumberFormatInfo();
  16. nfi.NumberDecimalSeparator = ".";
  17. Console.WriteLine("Podaj ścieżkę do pliku w którym chcesz zapisać wynik");
  18. path = Console.ReadLine();
  19. using(StreamWriter sw = new StreamWriter(path,true))
  20. {
  21. do
  22. {
  23. Console.Clear();
  24. Console.WriteLine("Odwracanie macierzy");
  25. Console.WriteLine();
  26. Console.WriteLine("Podaj rozmiar macierzy n=");
  27. str = Console.ReadLine();
  28. int.TryParse(str,out n);
  29. A = new double[n+1,2*n+1];
  30. for(i = 1;i <= n;i++)
  31. {
  32. Console.WriteLine("Wprowadz " + i.ToString(nfi) + ". wiersz macierzy");
  33. for(j = 1;j <= n;j++)
  34. {
  35. str = Console.ReadLine();
  36. double.TryParse(str,out A[i,j]);
  37. }
  38. }
  39. Inverse(A,n,out d);
  40. sw.WriteLine(d.ToString(nfi));
  41. for(i = 1;i <= n && d != 0.0 ;i++)
  42. {
  43. for(j = n + 1;j <= 2*n;j++)
  44. {
  45. Console.Write(A[i,j].ToString(nfi)+" , ");
  46. sw.Write(A[i,j].ToString(nfi) + " , ");
  47. }
  48. Console.WriteLine();
  49. sw.WriteLine();
  50. }
  51.  
  52. esc = (char)Console.ReadKey().Key;
  53. }
  54. while(esc != (char)ConsoleKey.Escape);
  55. }
  56. }
  57. public static void Inverse(double[,] A,int n,out double d)
  58. {
  59. int i,j,k,m;
  60. double s,t,temp;
  61. d = 1.0;
  62. for(i = 1;i <= n;i++)
  63. for(j = n+1;j <= 2*n;j++)
  64. if(i == j - n)
  65. A[i,j] = 1.0;
  66. else
  67. A[i,j] = 0.0;
  68. for(i = 1;i <= n;i++)
  69. {
  70. m = i;
  71. for(j = i;j <= n;j++)
  72. if(Math.Abs(A[j,i]) > Math.Abs(A[m,i]))
  73. m = j;
  74. for(j = 1;j <= 2*n;j++)
  75. {
  76. temp = A[i,j];
  77. A[i,j] = A[m,j];
  78. A[m,j] = temp;
  79. }
  80. if(m != i)
  81. d = -d;
  82. if(A[i,i] == 0.0)
  83. {
  84. d = 0.0;
  85. return;
  86. }
  87. s = A[i,i];
  88. for(j = 1;j <= 2*n;j++)
  89. A[i,j] /= s;
  90. for(j = i + 1;j <= n;j++)
  91. {
  92. t = A[j,i];
  93. for(k = i;k <= 2*n;k++)
  94. A[j,k]-=A[i,k]*t;
  95. }
  96. }
  97. for(k = n + 1;k <= 2*n;k++)
  98. {
  99. for(i = n;i >= 1;i--)
  100. {
  101. s = A[i,k];
  102. for(j = i + 1;j <= n;j++)
  103. s -= A[i,j]*A[j,k];
  104. A[i,k] = s;
  105. }
  106. }
  107. }
  108. }
  109. }
Advertisement
Add Comment
Please, Sign In to add comment