逆行列
3月になってしまいました。現在期末テスト真っ最中で*1、今週いっぱいで今年度の営業が終了します。
明日は、落とすと3年生になれなくなってしまう「線形代数Ⅱ」のテストで*2、お勉強中です。
で、逆行列とか久しく計算してなかったんですが(こんなんで大丈夫なのか...)、計算とか怪しくて正しく計算できてるか怖いのでコードを書いて確かめてみた。
ただですね、これはなかなかひどいコード。2*2の行列だけしか計算できないし、forとかforeachとか使ってないし。演算子のオーバーライドとかしたいし。まあ2*2だからまだ書けるんですが。
とりあえずこんなことしてないで演習を続けなければ。あとプリントあと3枚。
ということで
設計がおかしいだけではなく、「1 / ad-bc」がそもそも分数になってない。なおすのめんどくさい。近いうちになおす...
すごく間違ってるコード
実際には逆行列の計算を含んだ積算。
using System; namespace InverseMatrix { class Program { public class Matrix { public int a { get; set; } public int b { get; set; } public int c { get; set; } public int d { get; set; } public Matrix() { this.a = 0; this.b = 0; this.c = 0; this.d = 0; } public Matrix( int _a, int _b, int _c, int _d ) { this.a = _a; this.b = _b; this.c = _c; this.d = _d; } } public static Matrix Multiple( Matrix ma, Matrix mb ) { Matrix neo = new Matrix(); neo.a = ma.a * mb.a + ma.b * mb.c; neo.b = ma.a * mb.b + ma.b * mb.d; neo.c = ma.c * mb.a + ma.d * mb.c; neo.d = ma.c * mb.b + ma.d * mb.d; return neo; } public static Matrix GetInverse( Matrix matrix ) { Matrix neo = new Matrix(); int prefix = ( matrix.a * matrix.d ) - ( matrix.b * matrix.c ); if ( prefix > 0 ) { neo.a = 1 / prefix * matrix.d; neo.b = 1 / prefix * ( 0 - matrix.b ); neo.c = 1 /prefix * ( 0 - matrix.c ); neo.d = 1 / prefix * matrix.a; } else { Console.WriteLine( "Inverse-Matrix is not exist..." ); Console.ReadKey(); Environment.Exit( 0 ); } return neo; } static void Main( string[] args ) { Matrix Q = new Matrix( 2, 3, 1, 2 ); Matrix B = new Matrix( 2, 1, 3, 5 ); Matrix P = new Matrix( 1, 1, 1, 2 ); Matrix C = new Matrix(); C = GetInverse( Q ); C = Multiple( C, B ); C = Multiple( C, P ); Console.WriteLine( "{0}\t{1}\n{2}\t{3}", C.a, C.b, C.c, C.d ); Console.ReadKey(); } } }
実行例
例って言うか、コードに直書きしてるんだけどね。行列。
-18 -31 13 22
追記
ad-bc が0だと「0で除算しようとしました例外」がでるな。いや出ないけど、あれ、なんだかおかしくないか、コード。テストてすと。