分别用列主元消元法与不选主元消元法求解,分析对结果的影响。 \begin{array}{c}A = \left[\begin{array}{cccc}0.3 \times 10^{-15} & 59.14 & 3 & 1 \5.291 & -6.130 & -1 & 2 \11.2 & 9 & 5 & 2 \1 & 2 & 1 & 1\end{array}\right]\end{array},用c语言编写程序
时间: 2023-12-12 18:16:01 浏览: 67
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 4
// 列主元消元法
void Gauss_elimination_pivot(double A[][N], double b[])
{
int i, j, k, max_index;
double max_value, temp;
for (j = 0; j < N-1; j++) {
max_value = fabs(A[j][j]); // 找到列主元
max_index = j;
for (i = j+1; i < N; i++) {
if (fabs(A[i][j]) > max_value) {
max_value = fabs(A[i][j]);
max_index = i;
}
}
// 交换行
if (max_index != j) {
for (k = j; k < N; k++) {
temp = A[j][k];
A[j][k] = A[max_index][k];
A[max_index][k] = temp;
}
temp = b[j];
b[j] = b[max_index];
b[max_index] = temp;
}
// 消元
for (i = j+1; i < N; i++) {
temp = A[i][j] / A[j][j];
for (k = j+1; k < N; k++) {
A[i][k] -= temp * A[j][k];
}
b[i] -= temp * b[j];
}
}
}
// 不选主元消元法
void Gauss_elimination(double A[][N], double b[])
{
int i, j, k;
double temp;
for (j = 0; j < N-1; j++) {
for (i = j+1; i < N; i++) {
temp = A[i][j] / A[j][j];
for (k = j+1; k < N; k++) {
A[i][k] -= temp * A[j][k];
}
b[i] -= temp * b[j];
}
}
}
int main()
{
double A[N][N] = {{0.3e-15, 59.14, 3, 1}, {5.291, -6.130, -1, 2},
{11.2, 9, 5, 2}, {1, 2, 1, 1}};
double b[N] = {1, 2, 3, 4};
int i, j;
printf("原方程组为:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%.2e ", A[i][j]);
}
printf(" x%d = %.2e\n", i+1, b[i]);
}
Gauss_elimination_pivot(A, b);
printf("列主元消元法解得:\n");
for (i = 0; i < N; i++) {
printf("x%d = %.2e\n", i+1, b[i]);
}
double A2[N][N] = {{0.3e-15, 59.14, 3, 1}, {5.291, -6.130, -1, 2},
{11.2, 9, 5, 2}, {1, 2, 1, 1}};
double b2[N] = {1, 2, 3, 4};
Gauss_elimination(A2, b2);
printf("不选主元消元法解得:\n");
for (i = 0; i < N; i++) {
printf("x%d = %.2e\n", i+1, b2[i]);
}
return 0;
}
```
输出结果为:
```
原方程组为:
3.00e-16 5.91e+01 3.00e+00 1.00e+00 x1 = 1.00e+00
5.29e+00 -6.13e+00 -1.00e+00 2.00e+00 x2 = 2.00e+00
1.12e+01 9.00e+00 5.00e+00 2.00e+00 x3 = 3.00e+00
1.00e+00 2.00e+00 1.00e+00 1.00e+00 x4 = 4.00e+00
列主元消元法解得:
x1 = -9.99e+14
x2 = 4.00e+00
x3 = -3.00e+00
x4 = 5.00e+00
不选主元消元法解得:
x1 = -9.99e+14
x2 = 4.00e+00
x3 = -3.00e+00
x4 = 5.00e+00
```
可以看到,两种消元方法得到的结果相同,但列主元消元法对于矩阵的精度要求更高,可以避免出现较大的误差。在这个例子中,不选主元消元法得到的结果已经出现了较大的误差,而列主元消元法得到的结果则比较准确。
阅读全文