高斯消元法
// print matrix
void mprint(double a[][4]){
.....
}
// 定义求解方程的子程序,注意 虚参:x[]是数组, a是增广矩阵(a,b)
void gaussian_elimination(double x[], double a[][4]){
.....
}
int main() {
double a[3][4]={ {12, -3, 3, 15},{-18, 3, -1, -15}, {1, 1, 1, 6} };
double x[3];
// 调用子程序
gaussian_elimination(x,a);
for( int i=0;i<n;i++){
printf( "\n x[%d]= %f \n",i+1,x[i]);
}
return 0;
}
LU分解法
void LU_decomposition(double L[][n], double U[][n], double a[][n]){
....
}
int main() {
double a[n][n]={ {12,-3,3},{-18,3,-1},{1,1,1} } ;
double b[n]={15,-15,6};
double L[n][n],U[n][n] ;
// 调用LU子程序
LU_decomposition(L,U,a);
// out put L[][] and U[][]
.....
// back substitution of y[] by Ly = b
double x[n],y[n], xm;
y[0]=b[0];
for(int i=1;i<n;i++) {
xm=0;
for(int j=0;j<=i-1;j++) { xm +=..... ; }
y[i] = .... ;
}
// back substitution of x[] by Ux= y
x[n-1] = y[n-1] /U[n-1][n-1] ;
for(int i=n-2;i>=0;i--) {
xm =0;
for(int j=i+1;j<n;j++) { xm += ... ; }
x[i] = .... ;
}
// output solution x[]
.....
return 0;
}
三对角矩阵的追赶法
void tridiagonal_matrix_solve(double x[], const int n, double a[], double b[], double c[], double f[]){
//动态分配内存
double *d = (double*) malloc(n*sizeof(double) );
double *e = (double*) malloc(n*sizeof(double) );
//初始化e, d数组
....
......
}
//主程序调用
....