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;
}
|