//A = LU,其中L为单位下三角阵,U为上三角阵
#include <stdio.h>
#include <math.h>
void print_matrix(int row, int col, double matrix[row][col])
{
for(int i = 0;i < row; i++)
{
for(int j = 0;j < col; j++)
{
printf("%lf\t",matrix[i][j]);
}
printf("\n");
}
printf("----------------------------------------------");
printf("\n");
}
void print_vector(int n, double vector[n])
{
for(int i = 0;i < n;i ++)
{
printf("%.12lf\n",vector[i]);
}
printf("----------------------------------------------");
printf("\n");
}
int main()
{
int n = 3;
double A[3][3] = {{2, 1, 1}, {1, 3, 2}, {1, 2, 2}};//A[n][n]
double L[n][n];
for (int j = 0; j < n; j++)//initialize L = I
{
for (int k = 0; k < n; k++)
{
if (k == j)
{
L[j][k] = 1;
}
else
{
L[j][k] = 0;
}
}
}
double U[n][n];
for (int i = 0; i < n; i++)//initialize U = 0
{
for (int j = 0; j < n; j++)
{
U[i][j] = 0;
}
}
//get L, U
for (int k = 0; k < n; k++)
{
if (k == 0)
{
for (int j = k; j < n; j++)
{
U[k][j] = A[k][j];
}
for (int i = k+1; i < n; i++)
{
L[i][k] = A[i][k]/U[k][k];
}
}
else
{
for (int j = k; j < n; j++)
{
double sum1 = 0;
for (int r = 0; r <= k-1; r++)
{
sum1 = sum1 + L[k][r]*U[r][j];
}
U[k][j] = A[k][j] - sum1;
}
for (int i = k+1; i < n; i++)
{
double sum2 = 0;
for (int r = 0; r <= k-1; r++)
{
sum2 = sum2 + L[i][r]*U[r][k];
}
L[i][k] = (A[i][k] - sum2)/U[k][k];
}
}
}
//print A, L, U
printf("A = \n");
print_matrix(n, n, A);
printf("L = \n");
print_matrix(n, n, L);
printf("U = \n");
print_matrix(n, n, U);
//solve LY = b
double b[3] = {4, 6, 5};
double Y[n];
for (int i = 0; i < n; i++)//calculate Y
{
if (i == 0)
{
Y[i] = b[i];
}
else
{
double sum3 = 0;
for (int j = 0; j <= i-1; j++)
{
sum3 = sum3 + L[i][j]*Y[j];
}
Y[i] = b[i] - sum3;
}
}
//solve UX = Y
double X[n];
for (int i = n-1; i >= 0; i--)
{
if (i == n-1)
{
X[i] = Y[i]/U[i][i];
}
else
{
double sum4 = 0;
for (int j = i+1; j <n; j++)
{
sum4 = sum4 + U[i][j]*X[j];
}
X[i] = (Y[i] - sum4)/U[i][i];
}
}
//print Y, X
printf("Y = \n");
print_vector(n, Y);
printf("X = \n");
print_vector(n, X);
return 0;
}
矩阵Doolittle分解的C语言实现
最新推荐文章于 2024-08-19 22:10:14 发布