Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Globalization;
- namespace MatrixInverse
- {
- class MatrixInverse
- {
- public static void Main()
- {
- char esc;
- string str,path;
- int i,j,n;
- double[,] A;
- double d;
- NumberFormatInfo nfi = new NumberFormatInfo();
- nfi.NumberDecimalSeparator = ".";
- Console.WriteLine("Podaj ścieżkę do pliku w którym chcesz zapisać wynik");
- path = Console.ReadLine();
- using(StreamWriter sw = new StreamWriter(path,true))
- {
- do
- {
- Console.Clear();
- Console.WriteLine("Odwracanie macierzy");
- Console.WriteLine();
- Console.WriteLine("Podaj rozmiar macierzy n=");
- str = Console.ReadLine();
- int.TryParse(str,out n);
- A = new double[n+1,2*n+1];
- for(i = 1;i <= n;i++)
- {
- Console.WriteLine("Wprowadz " + i.ToString(nfi) + ". wiersz macierzy");
- for(j = 1;j <= n;j++)
- {
- str = Console.ReadLine();
- double.TryParse(str,out A[i,j]);
- }
- }
- Inverse(A,n,out d);
- sw.WriteLine(d.ToString(nfi));
- for(i = 1;i <= n && d != 0.0 ;i++)
- {
- for(j = n + 1;j <= 2*n;j++)
- {
- Console.Write(A[i,j].ToString(nfi)+" , ");
- sw.Write(A[i,j].ToString(nfi) + " , ");
- }
- Console.WriteLine();
- sw.WriteLine();
- }
- esc = (char)Console.ReadKey().Key;
- }
- while(esc != (char)ConsoleKey.Escape);
- }
- }
- public static void Inverse(double[,] A,int n,out double d)
- {
- int i,j,k,m;
- double s,t,temp;
- d = 1.0;
- for(i = 1;i <= n;i++)
- for(j = n+1;j <= 2*n;j++)
- if(i == j - n)
- A[i,j] = 1.0;
- else
- A[i,j] = 0.0;
- for(i = 1;i <= n;i++)
- {
- m = i;
- for(j = i;j <= n;j++)
- if(Math.Abs(A[j,i]) > Math.Abs(A[m,i]))
- m = j;
- for(j = 1;j <= 2*n;j++)
- {
- temp = A[i,j];
- A[i,j] = A[m,j];
- A[m,j] = temp;
- }
- if(m != i)
- d = -d;
- if(A[i,i] == 0.0)
- {
- d = 0.0;
- return;
- }
- s = A[i,i];
- for(j = 1;j <= 2*n;j++)
- A[i,j] /= s;
- for(j = i + 1;j <= n;j++)
- {
- t = A[j,i];
- for(k = i;k <= 2*n;k++)
- A[j,k]-=A[i,k]*t;
- }
- }
- for(k = n + 1;k <= 2*n;k++)
- {
- for(i = n;i >= 1;i--)
- {
- s = A[i,k];
- for(j = i + 1;j <= n;j++)
- s -= A[i,j]*A[j,k];
- A[i,k] = s;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment