fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. // 与えられたデータ点
  5. double x[] = {0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8, 3, 3.2, 3.4, 3.6, 3.8, 4, 4.2, 4.4, 4.6, 4.8, 5, 5.2, 5.4, 5.6, 5.8};
  6. double y[] = {1.91112, 2.35383, 2.46291, 2.5194, 3.24128, 3.17911, 3.84522, 3.6307, 4.57004, 5.3648, 5.34549, 5.66861, 6.47708, 7.04509, 8.19176, 9.08016, 9.42837, 10.636, 12.90674, 13.78106, 14.069, 15.74164, 19.03954, 18.72694, 20.00696, 23.52779, 24.77398, 26.93519, 32.92713, 38.9375};
  7. int n = 30; // データ点の数
  8.  
  9. // 指数関数の定義
  10. double exponential_func(double x, double a, double b) {
  11. return a * exp(b * x);
  12. }
  13.  
  14. // 最小二乗法によるフィッティング
  15. void fit_exponential(double x[], double y[], int n, double *a, double *b) {
  16. double sum_x = 0, sum_y = 0, sum_x2 = 0, sum_xy = 0, sum_ln_y = 0, sum_x_ln_y = 0;
  17. for (int i = 0; i < n; i++) {
  18. sum_x += x[i];
  19. sum_y += y[i];
  20. sum_x2 += x[i] * x[i];
  21. sum_xy += x[i] * y[i];
  22. sum_ln_y += log(y[i]);
  23. sum_x_ln_y += x[i] * log(y[i]);
  24. }
  25. double denominator = n * sum_x2 - sum_x * sum_x;
  26. *b = (n * sum_x_ln_y - sum_x * sum_ln_y) / denominator;
  27. *a = exp((sum_ln_y - *b * sum_x) / n);
  28. }
  29.  
  30. int main() {
  31. double a, b;
  32. fit_exponential(x, y, n, &a, &b);
  33. printf("フィッティングした指数関数: y = %f * exp(%f * x)\n", a, b);
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
フィッティングした指数関数: y = 2.011759 * exp(0.493650 * x)