fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6.  
  7.  
  8. double chord(double a, double b, double e, double (*f)(double))
  9. { // метод хорд
  10.  
  11. double fa = f(a), fb = f(b);
  12. if (fa*fb > 0) throw runtime_error("Wrong data");
  13.  
  14. for(;abs(b-a) > e;)
  15. {
  16. double x = a - (b-a)*fa/(fb-fa);
  17. b = a;
  18. fb = fa;
  19. a = x;
  20. fa = f(x);
  21. }
  22. return a;
  23. }
  24.  
  25. double dichotomy(double a, double b, double e, double (*f)(double))
  26. { //метод дихотомии
  27. double fa = f(a), fb = f(b);
  28. if (fa*fb > 0) throw runtime_error("Wrong data");
  29.  
  30. for(;abs(b - a) > e;)
  31. {
  32. double x = (a + b)/2;
  33. if (f(x)*fa > 0) a = x;
  34. else b = x;
  35. }
  36. return (a+b)/2;
  37. }
  38.  
  39. double g(double x)
  40. {
  41. return x * x * x - 18 * x - 83;
  42. }
  43.  
  44. double f(double x)
  45. {
  46. return x * x * x + 4 * x - 3;
  47. }
  48.  
  49. int main()
  50. {
  51. try {
  52. cout << chord(0,1,0.0001,f) << " vs " << dichotomy(0,1,0.0001,f) << "\n";
  53. cout << chord(2,10,0.0001,g) << " vs " << dichotomy(2,10,0.0001,g) << "\n";
  54. } catch(exception&e)
  55. {
  56. cerr << e.what() << endl;
  57. }
  58. }
  59.  
Success #stdin #stdout 0s 5520KB
stdin
Standard input is empty
stdout
0.673593  vs  0.673615
5.70512  vs  5.70511