fork(1) download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int main() {
  5. double x[8] = {0.15708, 0.23982, 0.37400, 0.57120, 0.82674, 1.04720, 1.23200, 1.43452};
  6. double y[8] = {0.98769, 0.97138, 0.93087, 0.84125, 0.67728, 0.50000, 0.33236, 0.13586};
  7.  
  8. double Sx2 = 0, Sx4 = 0, Sy = 0, Sx2y = 0;
  9.  
  10. for (int i = 0; i < 8; i++) {
  11. double x2 = x[i] * x[i];
  12. Sx2 += x2;
  13. Sx4 += x2 * x2;
  14. Sy += y[i];
  15. Sx2y += x2 * y[i];
  16. }
  17.  
  18. // Normal equation matrix
  19. double A11 = 8, A12 = Sx2;
  20. double A21 = Sx2, A22 = Sx4;
  21.  
  22. double B1 = Sy, B2 = Sx2y;
  23.  
  24. // Solve 2x2 system
  25. double det = A11 * A22 - A12 * A21;
  26. double a1 = ( B1 * A22 - A12 * B2 ) / det;
  27. double a2 = ( A11 * B2 - B1 * A21 ) / det;
  28.  
  29. printf("Model 1 coefficients:\n");
  30. printf("a1 = %.6f\n", a1);
  31. printf("a2 = %.6f\n", a2);
  32.  
  33. // Compute squared error
  34. double E = 0;
  35. for (int i = 0; i < 8; i++) {
  36. double yhat = a1 + a2 * x[i] * x[i];
  37. double diff = y[i] - yhat;
  38. E += diff * diff;
  39. }
  40.  
  41. printf("Squared error E = %.10f\n", E);
  42.  
  43. printf("\nModel 1 predicted values:\n");
  44. for (int i = 0; i < 8; i++) {
  45. double yhat = a1 + a2 * x[i] * x[i];
  46. printf("%f\n", yhat);
  47. }
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Model 1 coefficients:
a1 = 0.985005
a2 = -0.423999
Squared error E = 0.0016966201

Model 1 predicted values:
0.974543
0.960619
0.925697
0.846667
0.695202
0.520035
0.341448
0.112479