此代码用于查找矩阵的逆,几乎可以做到这一点。最后一行数字不正确,我不确定为什么。这不是找到逆数的最佳方法,但是这是我需要做的作业。我已经多次修改了幂函数,所以现在应该是正确的。使用的方法是B = I-A,A ^ -1 = I + B + B ^ 2 + B ^ 3 ...(一直到B ^ 20)。
#include <iostream>
#include <iomanip>
using namespace std;
void multiplinator(double invA[][3], double A[][3], double y[][3]) //multiplies the matrix
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
y[i][j] = 0;
for(int k = 0; k < 3; k++)
{
y[i][j] += invA[i][k] * A[k][j];
}
}
}
}
void printinator(double a[3][3]) //prints a matrix
{
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++)
cout << fixed << setprecision(2) << setw(12) << a[i][j] << " ";
cout << endl;
}
cout << endl;
}
void substitinator(double I[][3], double A[][3], double B[][3]) //Matrix subtraction
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
B[i][j] = I[i][j] - A[i][j];
}
void additinator(double I[3][3], double B[][3], double invA[][3]) //Matrix addition
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
invA[i][j] = I[i][j] + B[i][j];
}
void powernator(double B[][3],double pB[][3], int p) //function which is supposed to raise a matrix to a certain power
{
double temp[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
int i,j,w,k;
for(i = 0 ; i < 2 ; ++ i )
for(j = 0 ; j < 2 ; ++ j )
pB[i][j] = ( i == j ) ;
for(w = 0; w < p; w++)
{
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
temp[i][j]=0;
for(k=0;k<2;k++)
{
temp[i][j] += pB[i][k] * B[k][j];
}
}
}
for(i = 0; i < 2; i++){
for(j = 0; j < 2; j++)
{
pB[i][j] = temp[i][j];
}
}
}
}
void gettem(double pB[][3], double invA[][3]) //Matrix addition of power of B
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
invA[i][j] += pB[i][j];
}
int main()
{
double A[3][3] = { {1./2, 1, 0} , {0, 2./3, 0} , {-1./2, -1, 2./3} };
double invA[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
double I[3][3] = { {1, 0, 0} , {0, 1, 0} , {0, 0, 1} };
double B[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
double pB[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
double y[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
substitinator(I,A,B);
additinator(I,B,invA);
for(int p = 2; p <= 20; p++)
{
powernator(B,pB,p);
gettem(pB, invA);
}
cout << "\n\t\t Inverse:" << endl;
printinator(invA);
cout << "\n\t\t invA * A:" << endl;
multiplinator(invA, A, y);
printinator(y);
}
我同意@ 1201ProgramAlarm,您的powernator()
函数错误,应确保所有for循环条件都是< 3
而不是< 2
void powernator(double B[3][3],double pB[3][3], int p) //function which is supposed to raise a matrix to a certain power
{
double temp[3][3] = { {0, 0, 0} , {0, 0, 0} , {0, 0, 0} };
int i,j,w,k;
for(i = 0 ; i < 3 ; ++ i )
for(j = 0 ; j < 3 ; ++ j )
pB[i][j] = ( i == j ) ;
for(w = 0; w < p; w++)
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
temp[i][j]=0;
for(k=0;k<3;k++)
{
temp[i][j] += pB[i][k] * B[k][j];
}
}
}
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++)
{
pB[i][j] = temp[i][j];
}
}
}
}
结果是:
Inverse:
2.00 -3.00 0.00
0.00 1.50 0.00
1.50 0.00 1.50
invA * A:
1.00 0.00 0.00
0.00 1.00 0.00
-0.00 0.00 1.00
希望这会有所帮助。