高斯消元法求解线性方程组拟合三元一次方程

20211213 作业

lucas

理论分析

根据凸函数性质,在梯度得零得地方求得最小值。 故,可列线性方程组Ax=B,利用高斯消元法可以求得w。

算法设计

graph A[输入数据] --> B(计算AB) B-->C[利用高斯消元法求解w] C-->D[验证结果误差]

算法实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#pragma warning(disable:4996)
double calab(double ** a,double * b,double** x, double* y, double* w, int m, int n) {
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            a[i][j] = 0;
            for (int k = 0; k < m; k++) {
                a[i][j] += x[k][j] * x[k][i];
            }
        }
        b[i] = 0;
        for (int k = 0; k < m; k++) {
            b[i] += y[k] * x[k][i];
        }
    }
}
double* gauss(double** a, double* b, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j <= n; j++) {
            double e = a[j][i] / a[i][i];
            a[j][i] = 0;
            b[j] -= b[i] * e;
            for (int k = i+1; k <= n; k++) {
                a[j][k] -= a[i][k] * e;
            }
        }
    }
    double* result = (double*)calloc(n + 1, sizeof(double));
    for (int i = n; i >= 0; i--) {
        double w = b[i];
        for (int j = n; j > i; j--) {
            w -= a[i][j] * result[j];
        }
        result[i] = w / a[i][i];
    }
    return result;
}
int main() {
    int m, n;
    scanf("%d%d", &m, &n);
    double* w = (double*)calloc(n+1, sizeof(double));
    double** X = (double**)calloc(m, sizeof(double*));
    for (int i = 0; i < m; i++)X[i] = (double*)calloc(n+1, sizeof(double));
    double* Y = (double*)calloc(m, sizeof(double));
    for (int i = 0; i < m; i++) {
        scanf("%lf", &Y[i]);
        X[i][0] = 1;
        for (int j = 1; j <= n; j++) scanf("%lf", &X[i][j]);
    }
    double** A = (double**)calloc(n + 1, sizeof(double*));
    for (int i = 0; i < n + 1; i++)A[i] = (double*)calloc(n + 1, sizeof(double));
    double* B = (double*)calloc(n + 1, sizeof(double));
    calab(A, B, X, Y, w, m, n);
    double* result = gauss(A, B, n);
    double check[19] = {0};
    for (int i = 0; i < 19; i++) {
        for (int j = 0; j <= n; j++) {
            check[i] += result[j] * X[i][j];
        }
    }
    double d[19] = { 0 };
    double count = 0;
    for (int i = 0; i < 19; i++)count+=fabs(d[i] = Y[i] - check[i]);
    for (int i = 0; i <= n; i++)printf("w%d=%f\n", i, result[i]);
    printf("average d = %f", count / 19);
    
    return 0;
}

测试分析及结果

输入所给数据后结果如下,平均偏差等于0.716

京ICP备2021032224号-1
Built with Hugo
主题 StackJimmy 设计
vi ./themes/hugo-theme-learn/layouts/partials/footer.html