我这里有一段程序关于LU分解的,贴出来,大家给点意见,感激~
vv= new double[rows];//vv stores the implicit scaling of each row
indx= new int[rows];//indx is an output vector which records the row permutation effected by the partial pivoting
int rmax=0;
double TINY=1.0E-305;
for(int r=0;r<rows;r++)// find out the max value per row
{
double Max=0.0;
for(int c=0;c<cols;c++)
{
double temp=fabs(Get(r,c));
if(temp>Max)
Max=temp;
}
if(Max<TINY)// if the max value less than the tiny, it's a singular matrix
{
cout<<"Singular matrix"<<endl;
exit(0);
}
vv[r]=1.0/Max;// row r's scale factor
}
for (int c=0;c<cols;c++)// for r<c: find out the elements of U, and put them in the posation of the former matrix
{
if(c>0)
{
for(int r=0;r<c;r++)
{
double sum=Get(r,c);
if(r>0)
{
for(int k=0;k<r;k++)sum=sum-Get(r,k)*Get(k,c);
Set(r,c,sum);
}
}
}
double Max=0.0;
for(int r=c;r<rows;r++)//for r=c r<rows: find out the L,and put them in the posation of the former matrix
{
double sum=Get(r,c);
if(c>0)
{
for(int k=0;k<c;k++) sum=sum- Get(r,k)*Get(k,c);
Set(r,c,sum);
}
double dum=vv[r]*fabs(sum);
if(dum>= Max)
{
Max=dum;
rmax=r;
}
}
if(Max<TINY)
{
cout<<"Singular matrix"<<endl;
exit(0);
}
if(c!=rmax)// change rows, put the max value in the right persation
{
for (int k=0;k<cols;k++)
{
double a,b;
a=Get(rmax,k);
b=Get(c,k);
Set(rmax,k,b);
Set(c,k,a);
}
double dum= vv[c];
vv[c]=vv[rmax];
vv[rmax]=dum;
/*vv[rmax]=vv[c];*/ //also change the scale factor
}
indx[c]=rmax;
if( c!=cols-1)//divide by the pivot element
{
double a=Get(c,c);
if(a==0) a=TINY;
double dum=1.0/Get(c,c);
for(int r=c+1; r<rows;r++)
Set(r,c,Get(r,c)*dum);
}
}