|
分類:[C#]
逆行列の計算ができません コンソールアプリケーションです コードは以下の通りです。三角行列まではできました。このあとどうすればいいのでしょう
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { double[,] x = new double[10, 11]; string line; string[] ndata = new string[10]; int i, j, n, m; using (StreamReader buff = new StreamReader(@"mat1.txt")) { m = 0; while ((line = buff.ReadLine()) != null) { ndata = Regex.Split(line, @"(\s+)"); n = 0; for (i = 0; i < ndata.Length; i = i + 2) { x[m, n] = double.Parse(ndata[i]); n = n + 1; } m = m + 1; } n = (ndata.Length + 1) / 2; } inverse(ref x, m); for (i = 0; i < m; i++) { for (j = 0; j < (n - 1); j++) { Console.Write(@"{0:f4}", x[i, j]); Console.Write(" "); } Console.WriteLine(@"{0:f4}", x[i, (n - 1)]); } Console.Read(); } static void inverse(ref double[,] a, int m) { int i, imax, j, k; double xmax, buf, limit; limit = 1e-6; for (i = 0; i < m; i++) { imax = i; xmax = Math.Abs(a[i, i]); for (j = i + 1; j < m; j++) { buf = Math.Abs(a[j, i]); if (buf > xmax) { xmax = buf; imax = j; } } if (imax != i) { for (j = i; j < 2 * m; j++) { buf = a[i, j]; a[i, j] = a[imax, j]; a[imax, j] = buf; } } buf = a[i, i]; if (Math.Abs(buf) > limit) { buf = 1 / buf; for (j = i; j < 2 * m; j++) { a[i, j] = a[i, j] * buf; } } else { Console.WriteLine("singular"); return; } for (j = i + 1; j < m; j++) { buf = -a[j, i]; for (k = i; k < 2 * m; k++) { a[j, k] = a[j, k] + buf * a[i, k]; } } } for (i = m - 1; i >= 0; i = i - 1) { for (k = m; k < 2 * m; k++)// { buf = a[i, k];
for (j = i + 1; j < m; j++) {
buf = buf - a[i, j] * a[j, k];
}
a[i, k] = buf; } }
} } }
|