本文实例讲述了java实现的求逆矩阵算法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
package demo; public class matrixinverse { public static double det( double [][]matrix, int n) //计算n阶行列式(n=n-1) { int t0; int t1; int t2; double num; int cha; double [][] b; if (n> 0 ) { cha= 0 ; b= new double [n][n]; num= 0 ; if (n== 1 ) { return matrix[ 0 ][ 0 ]*matrix[ 1 ][ 1 ]-matrix[ 0 ][ 1 ]*matrix[ 1 ][ 0 ]; } for (t0= 0 ;t0<=n;t0++) //t0循环 { for (t1= 1 ;t1<=n;t1++) //t1循环 { for (t2= 0 ;t2<=n- 1 ;t2++) //t2循环 { if (t2==t0) { cha= 1 ; } b[t1- 1 ][t2]=matrix[t1][t2+cha]; } //t2循环 cha= 0 ; } //t1循环 num=num+matrix[ 0 ][t0]*det(b,n- 1 )*math.pow((- 1 ),t0); } //t0循环 return num; } else if (n== 0 ) { return matrix[ 0 ][ 0 ]; } return 0 ; } public static double inverse( double [][]matrix, int n, double [][]matrixc){ int t0; int t1; int t2; int t3; double [][]b; double num= 0 ; int chay= 0 ; int chax= 0 ; b= new double [n][n]; double add; add= 1 /det(matrix,n); for ( t0= 0 ;t0<=n;t0++) { for (t3= 0 ;t3<=n;t3++) { for (t1= 0 ;t1<=n- 1 ;t1++) { if (t1<t0) { chax= 0 ; } else { chax= 1 ; } for (t2= 0 ;t2<=n- 1 ;t2++) { if (t2<t3) { chay= 0 ; } else { chay= 1 ; } b[t1][t2]=matrix[t1+chax][t2+chay]; } //t2循环 } //t1循环 det(b,n- 1 ); matrixc[t3][t0]=det(b,n- 1 )*add*(math.pow(- 1 , t0+t3)); } } return 0 ; } public static void main(string[]args) //测试 { double [][] testmatrix = { { 1 , 22 , 34 , 22 }, { 1 , 11 , 5 , 21 } , { 0 , 1 , 5 , 11 }, { 7 , 2 , 13 , 19 }}; double [][]inmatrix= new double [ 4 ][ 4 ]; inverse(testmatrix, 3 ,inmatrix); string str= new string( "" ); for ( int i= 0 ;i< 4 ;i++) { for ( int j= 0 ;j< 4 ;j++) { string strr=string.valueof(inmatrix[i][j]); str+=strr; str+= " " ; } str+= "\n" ; } system.out.println( "服务器之家测试结果:" ); system.out.println(str); } } |
运行结果:
希望本文所述对大家java程序设计有所帮助。
原文链接:http://blog.csdn.net/u014581901/article/details/50805054