fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPS 1e-5
  5.  
  6. // Function
  7. double f(double x) {
  8. return x*x - 1 - sin(x);
  9. }
  10.  
  11. // Bisection Method (二分法)
  12. double bisection(double a, double b, int *iterations) {
  13. double mid;
  14. *iterations = 0;
  15.  
  16. while (1) {
  17. (*iterations)++;
  18. mid = (a + b) / 2.0;
  19.  
  20. if (fabs(f(mid)) < EPS) return mid;
  21.  
  22. if (f(a) * f(mid) < 0)
  23. b = mid;
  24. else
  25. a = mid;
  26. }
  27. }
  28.  
  29. // False Position Method (はさみうち法)
  30. double false_position(double a, double b, int *iterations) {
  31. double x;
  32. *iterations = 0;
  33.  
  34. while (1) {
  35. (*iterations)++;
  36. x = (a * f(b) - b * f(a)) / (f(b) - f(a));
  37.  
  38. if (fabs(f(x)) < EPS) return x;
  39.  
  40. if (f(a) * f(x) < 0)
  41. b = x;
  42. else
  43. a = x;
  44. }
  45. }
  46.  
  47. int main() {
  48. double r1, r2;
  49. int it1, it2;
  50.  
  51. printf("========================================\n");
  52. printf(" Solving f(x) = x^2 - 1 - sin(x) = 0\n");
  53. printf("========================================\n");
  54.  
  55. // ---- Bisection ----
  56. printf("\n[ Bisection Method ]\n");
  57.  
  58. r1 = bisection(-1.0, 0.0, &it1);
  59. printf("Interval [-1,0]: Root = %.6f, Iterations = %d\n", r1, it1);
  60.  
  61. r2 = bisection(1.0, 2.0, &it2);
  62. printf("Interval [1,2]: Root = %.6f, Iterations = %d\n", r2, it2);
  63.  
  64. // ---- False Position ----
  65. printf("\n[ False Position Method ]\n");
  66.  
  67. r1 = false_position(-1.0, 0.0, &it1);
  68. printf("Interval [-1,0]: Root = %.6f, Iterations = %d\n", r1, it1);
  69.  
  70. r2 = false_position(1.0, 2.0, &it2);
  71. printf("Interval [1,2]: Root = %.6f, Iterations = %d\n", r2, it2);
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
========================================
 Solving f(x) = x^2 - 1 - sin(x) = 0
========================================

[ Bisection Method ]
Interval [-1,0]: Root = -0.636734, Iterations = 16
Interval [1,2]: Root = 1.409622, Iterations = 16

[ False Position Method ]
Interval [-1,0]: Root = -0.636732, Iterations = 6
Interval [1,2]: Root = 1.409622, Iterations = 9