fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPS 1e-5
  5.  
  6. double f(double x) {
  7. return x*x - 1 - sin(x);
  8. }
  9.  
  10. // 二分法
  11. double bisection(double a, double b) {
  12. double mid;
  13.  
  14. while (1) {
  15. mid = (a + b) / 2.0;
  16.  
  17. if (fabs(f(mid)) < EPS) return mid;
  18.  
  19. if (f(a) * f(mid) < 0)
  20. b = mid;
  21. else
  22. a = mid;
  23. }
  24. }
  25.  
  26. // はさみうち法(False Position)
  27. double false_position(double a, double b) {
  28. double x;
  29.  
  30. while (1) {
  31. x = (a * f(b) - b * f(a)) / (f(b) - f(a));
  32.  
  33. if (fabs(f(x)) < EPS) return x;
  34.  
  35. if (f(a) * f(x) < 0)
  36. b = x;
  37. else
  38. a = x;
  39. }
  40. }
  41.  
  42. int main() {
  43. double r1, r2;
  44.  
  45. printf("=== Bisection Method ===\n");
  46. r1 = bisection(-1.0, 0.0);
  47. r2 = bisection(1.0, 2.0);
  48. printf("Roots: %.6f, %.6f\n", r1, r2);
  49.  
  50. printf("\n=== False Position Method ===\n");
  51. r1 = false_position(-1.0, 0.0);
  52. r2 = false_position(1.0, 2.0);
  53. printf("Roots: %.6f, %.6f\n", r1, r2);
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
=== Bisection Method ===
Roots: -0.636734, 1.409622

=== False Position Method ===
Roots: -0.636732, 1.409622