编辑代码

#include <stdio.h>
#include <math.h>

void polynomial_fit(int degree, double x[], double y[], int n, double coeffs[], double *error);

int main() {
    double x[] = {-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6};
    double y[] = {13.4, 7.2, 2.7, 1.2, 0.6, 3.1, 6.9, 12.5, 20.8, 31.7, 44.0};
    int n = sizeof(x) / sizeof(x[0]); 

    double coeffs[4]; 
    double error;

    for (int degree = 1; degree <= 3; degree++) {
        polynomial_fit(degree, x, y, n, coeffs, &error);

        printf("Degree %d polynomial:\n", degree);
        printf("y = ");
        for (int i = 0; i <= degree; i++) {
            printf("%+.3fx^%d ", coeffs[i], i);
        }
        printf("\nError E = %.3f\n\n", error);
    }

    return 0;
}

void polynomial_fit(int degree, double x[], double y[], int n, double coeffs[], double *error) {
    int i, j, k;
    double X[2 * degree + 1]; 
    double B[degree + 1];    
    double A[degree + 1][degree + 2]; 

    for (i = 0; i < 2 * degree + 1; i++) {
        X[i] = 0;
        for (j = 0; j < n; j++) {
            X[i] += pow(x[j], i);
        }
    }

    for (i = 0; i <= degree; i++) {
        B[i] = 0;
        for (j = 0; j < n; j++) {
            B[i] += pow(x[j], i) * y[j];
        }
    }

    for (i = 0; i <= degree; i++) {
        for (j = 0; j <= degree; j++) {
            A[i][j] = X[i + j];
        }
        A[i][degree + 1] = B[i];
    }

    for (i = 0; i <= degree; i++) {
        for (k = i + 1; k <= degree; k++) {
            double t = A[k][i] / A[i][i];
            for (j = 0; j <= degree + 1; j++) {
                A[k][j] -= t * A[i][j];
            }
        }
    }

    for (i = degree; i >= 0; i--) {
        coeffs[i] = A[i][degree + 1];
        for (j = i + 1; j <= degree; j++) {
            coeffs[i] -= A[i][j] * coeffs[j];
        }
        coeffs[i] /= A[i][i];
    }

    *error = 0;
    for (i = 0; i < n; i++) {
        double yi = 0;
        for (j = 0; j <= degree; j++) {
            yi += coeffs[j] * pow(x[i], j);
        }
        *error += pow(y[i] - yi, 2);
    }
}