用c语言写LU分解代码
时间: 2023-06-09 15:07:46 浏览: 107
以下是一个使用C语言实现的LU分解代码示例:
#include <stdio.h>
#define N 3
int main()
{
float mat[N][N] = {{6, -4, 1}, {-4, 6, -4}, {1, -4, 6}};
float L[N][N] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
float U[N][N] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
// LU分解
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
float sum = 0;
for (int k = 0; k < i; k++) {
sum += L[i][k] * U[k][j];
}
U[i][j] = mat[i][j] - sum;
}
for (int j = i; j < N; j++) {
if (i == j) {
L[i][i] = 1;
} else {
float sum = 0;
for (int k = 0; k < i; k++) {
sum += L[j][k] * U[k][i];
}
L[j][i] = (mat[j][i] - sum) / U[i][i];
}
}
}
// 打印结果
printf("输入矩阵:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%6.2f", mat[i][j]);
}
printf("\n");
}
printf("L矩阵:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%6.2f", L[i][j]);
}
printf("\n");
}
printf("U矩阵:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%6.2f", U[i][j]);
}
printf("\n");
}
return 0;
}
阅读全文