直接三角分解法求线性方程c语言
时间: 2023-06-10 14:07:22 浏览: 127
三角分解法是一种用于求解线性方程组的常见方法,可以通过高斯消元法对系数矩阵进行变换得到上三角矩阵,进而通过回代求解出未知数的值。以下是使用C语言实现三角分解法求解线性方程组的示例代码:
```c
#include <stdio.h>
#define N 3
void print_matrix(double a[][N+1], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= n; j++) {
printf("%10.6f ", a[i][j]);
}
printf("\n");
}
printf("\n");
}
void swap_rows(double a[][N+1], int i, int j) {
for (int k = 0; k <= N; k++) {
double tmp = a[i][k];
a[i][k] = a[j][k];
a[j][k] = tmp;
}
}
void gaussian_elimination(double a[][N+1], int n) {
for (int k = 0; k < n; k++) {
// find pivot row
int max_row = k;
for (int i = k+1; i < n; i++) {
if (a[i][k] > a[max_row][k]) {
max_row = i;
}
}
if (a[max_row][k] == 0) {
continue; // singular matrix, skip this column
}
// swap rows
swap_rows(a, k, max_row);
// eliminate lower rows
for (int i = k+1; i < n; i++) {
double factor = a[i][k] / a[k][k];
for (int j = k; j <= n; j++) {
a[i][j] -= factor * a[k][j];
}
}
}
}
void back_substitution(double a[][N+1], int n, double x[]) {
for (int i = n-1; i >= 0; i--) {
double sum = 0;
for (int j = i+1; j < n; j++) {
sum += a[i][j] * x[j];
}
x[i] = (a[i][n] - sum) / a[i][i];
}
}
int main() {
double a[N][N+1] = {{1, 2, 3, 9},
{2, 5, 2, 4},
{3, 1, 1, 8}};
double x[N];
printf("Original matrix:\n");
print_matrix(a, N);
gaussian_elimination(a, N);
printf("Upper triangular matrix:\n");
print_matrix(a, N);
back_substitution(a, N, x);
printf("Solution:\n");
for (int i = 0; i < N; i++) {
printf("x[%d] = %10.6f\n", i, x[i]);
}
return 0;
}
```
这个程序可以求解一个三元一次方程组,例如:
```
1x + 2y + 3z = 9
2x + 5y + 2z = 4
3x + 1y + 1z = 8
```
使用三角分解法求解这个方程组的结果为:
```
x[0] = -1.000000
x[1] = 2.000000
x[2] = 3.000000
```
这个结果表明,方程组的解为 x=-1,y=2,z=3。
阅读全文