fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cassert>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7.  
  8. //Метод деления отрезка пополам
  9. double bisekcii(double a, double b, double e, int& i, double (*f)(double))
  10. {
  11. i = 0;
  12. double fa = f(a), fb = f(b);
  13. assert(fa*fb < 0);
  14. while(b-a >= e)
  15. {
  16. double c=(a+b)/2;
  17. double fc = f(c);
  18. if (fa*fc <= 0)
  19. b=c;
  20. else
  21. a=c;
  22. i++;
  23. }
  24. return (a+b)/2.0;
  25. }
  26.  
  27.  
  28. double iteracii(double x, double e, int& i, double (*f)(double))
  29. {
  30. i=0;
  31.  
  32. double y = f(x);
  33.  
  34. while(fabs(y-x) >=e )
  35. {
  36. x = y;
  37. y = f(x);
  38. i++;
  39. }
  40. return y;
  41. }
  42.  
  43. double f1(double x)
  44. {
  45. return 1/(1.2*tan(x)+sqrt(x+1))-x;
  46. }
  47.  
  48. double f2(double x)
  49. {
  50. double z = (sin(x)+cos(x));
  51.  
  52. return z*z/pow(33.5,2./3)+sqrt(3./7);
  53. }
  54.  
  55. double f3(double x)
  56. {
  57. return f2(x)-x;
  58. }
  59.  
  60. int main(int argc, char * argv[])
  61. {
  62. int it;
  63. cout << bisekcii(0,2,1e-8,it,f1);
  64. cout << " Iterations: " << it << endl;
  65.  
  66. cout << iteracii(0,1e-8,it,f2);
  67. cout << " Iterations: " << it << endl;
  68.  
  69. cout << bisekcii(0,2,1e-8,it,f3);
  70. cout << " Iterations: " << it << endl;
  71.  
  72. }
  73.  
Success #stdin #stdout 0.01s 5428KB
stdin
Standard input is empty
stdout
0.520548  Iterations: 28
0.846395  Iterations: 5
0.846395  Iterations: 28