fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int main(void) {
  5. double a = 0.0, b = 4.0, m;
  6. double fa, fb, fm;
  7. double x = 3.0, fx, dfx, xn;
  8. double min = 1e-6;
  9. int ia = 0, ib = 0;
  10.  
  11. fa = cos(a/2.0);
  12. fb = cos(b/2.0);
  13.  
  14. // 二分法
  15. while (1) {
  16. m = (a + b) / 2.0;
  17. fm = cos(m/2.0);
  18. ia++;
  19. if (fabs(fm) < min) break;
  20. if (fa * fm < 0.0) {
  21. b = m;
  22. fb = fm;
  23. } else {
  24. a = m;
  25. fa = fm;
  26. }
  27. }
  28.  
  29. // ニュートン法
  30. while (1) {
  31. fx = cos(x/2.0);
  32. dfx = -0.5 * sin(x/2.0);
  33. ib++;
  34. xn = x - fx/dfx;
  35. x = xn;
  36. if (fabs(cos(x/2.0)) < min) break;
  37. }
  38.  
  39. printf("二分法の反復回数 = %d\n", ia);
  40. printf("ニュートン法の反復回数 = %d\n", ib);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
二分法の反復回数 = 19
ニュートン法の反復回数 = 2