Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.1 kB
8
Indexable
Never
#include <stdio.h>

int main() {
    float x[10], y[10], a[3][4];
    int n, i, j, k;
    
    printf("Enter number of data points: ");
    scanf("%d", &n);
    
    printf("Enter data points x[i], y[i]: \n");
    for (i = 0; i < n; i++) {
        scanf("%f %f", &x[i], &y[i]);
    }
    
    // Calculate sums
    float sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0, sum_x2y = 0;
    for (i = 0; i < n; i++) {
        sum_x += x[i];
        sum_y += y[i];
        sum_xy += x[i] * y[i];
        sum_x2 += x[i] * x[i];
        sum_x3 += x[i] * x[i] * x[i];
        sum_x2y += x[i] * x[i] * y[i];
        sum_x4 += x[i] * x[i] * x[i] * x[i];
    }
    
    // Fill matrix
    a[0][0] = n;
    a[0][1] = a[1][0] = sum_x;
    a[0][2] = a[1][1] = a[2][0] = sum_x2;
    a[0][3] = sum_y;
    a[1][2] = a[2][1] = sum_x3;
    a[1][3] = sum_xy;
    a[2][2] = sum_x4;
    a[2][3] = sum_x2y;
    
    // Print matrix
    printf("\nThe matrix is:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j <= 3; j++)
            printf("%.2f\t", a[i][j]);
        printf("\n");
    }
    
    // Gauss elimination
    for (i = 0; i < 2; i++) {
        for (k = i + 1; k < 3; k++) {
            double t = a[k][i] / a[i][i];
            for (j = 0; j <= 3; j++)
                a[k][j] = a[k][j] - t * a[i][j];
        }
    }
    
    // Print matrix after Gauss elimination
    printf("\n\nThe matrix after gauss-elimination is as follows:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j <= 3; j++)
            printf("%.2f\t", a[i][j]);
        printf("\n");
    }
    
    // Back-substitution
    float x_vals[3];
    for (i = 2; i >= 0; i--) {
        x_vals[i] = a[i][3];
        for (j = i + 1; j < 3; j++) {
            if (j != i)
                x_vals[i] -= a[i][j] * x_vals[j];
        }
        x_vals[i] /= a[i][i];
    }
    
    // Print values of variables
    printf("\nThe values of the variables are as follows:\n");
    for (i = 0; i < 3; i++)
        printf("%.2f\n", x_vals[i]);
    
    return 0;
}
Leave a Comment