fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPS 0.00000001
  5. #define N 1000
  6.  
  7. typedef struct {
  8. double ans;
  9. int iter;
  10. } Ans;
  11.  
  12. double f(double x)
  13. {
  14. return 0.5 - x + 0.2 * sin(x);
  15. }
  16.  
  17. /* f'(x) */
  18. double f2(double x)
  19. {
  20. return -1.0 + 0.2 * cos(x);
  21. }
  22.  
  23. double g(double x)
  24. {
  25. return 0.5 + 0.2 * sin(x);
  26. }
  27.  
  28. Ans linear_iteration_method(double x, double (*f)(double))
  29. {
  30. double x0;
  31. int i = 0;
  32. Ans ans;
  33.  
  34. do {
  35. x0 = x;
  36. x = f(x);
  37. i++;
  38. } while (fabs(x - x0) > EPS);
  39.  
  40. ans.ans = x;
  41. ans.iter = i;
  42.  
  43. return ans;
  44. }
  45.  
  46. Ans aitken_deltasquare_process(double a[], double b[])
  47. {
  48. int i;
  49. double dx1, dx2;
  50. Ans ans;
  51.  
  52. for (i = 0; i < N - 2; i++) {
  53. dx1 = a[i + 1] - a[i];
  54. dx2 = a[i + 2] - a[i + 1];
  55. b[i] = a[i + 2] - dx2 * dx2 / (dx2 - dx1);
  56. if (fabs(b[i] - a[i + 2]) <= EPS)
  57. break;
  58. }
  59.  
  60. ans.ans = b[i];
  61. ans.iter = i + 1;
  62.  
  63. return ans;
  64. }
  65.  
  66. Ans newton_method(double x, double (*f)(double), double (*f2)(double))
  67. {
  68. int i = 0;
  69. double x0;
  70. Ans ans;
  71.  
  72. do {
  73. x0 = x;
  74. x = x - f(x) / f2(x);
  75. i++;
  76. } while (fabs(x0 - x) > EPS);
  77.  
  78. ans.ans = x;
  79. ans.iter = i;
  80.  
  81. return ans;
  82. }
  83.  
  84. int main(void)
  85. {
  86. int i;
  87. double x0 = 0.2;
  88. Ans ans;
  89. static double a[N], b[N];
  90.  
  91. puts("線形反復法");
  92. ans = linear_iteration_method(x0, g);
  93. printf("solution = %.8f, iteration = %d\n", ans.ans, ans.iter);
  94.  
  95. puts("エイトケンのデルタ2乗法");
  96. /* 元数列の生成 */
  97. a[0] = x0;
  98. for (i = 1; i < N; i++)
  99. a[i] = g(a[i - 1]);
  100. ans = aitken_deltasquare_process(a, b);
  101. printf("solution = %.8f, iteration = %d\n", ans.ans, ans.iter);
  102.  
  103. puts("ニュートン法");
  104. ans = newton_method(x0, f, f2);
  105. printf("solution = %.8f, iteration = %d\n", ans.ans, ans.iter);
  106.  
  107. return 0;
  108. }
  109.  
Success #stdin #stdout 0.01s 1732KB
stdin
Standard input is empty
stdout
線形反復法
solution = 0.61546817, iteration = 11
エイトケンのデルタ2乗法
solution = 0.61546817, iteration = 9
ニュートン法
solution = 0.61546817, iteration = 4