fork download
  1. #include <cmath>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. double functionA(double x) {
  7. return sin(2.0 * x) - 1.0 + x;
  8. }
  9.  
  10. double functionB(double x) {
  11. return 2.0 * x / (1.0 + x / 1.5);
  12. }
  13.  
  14. double bisectionMethod(double (*function)(double), double a, double b, double tolerance) {
  15. double x;
  16. double f;
  17. double error = tolerance + 1;
  18. int step = 0;
  19. double fa = (*function)(a);
  20. double fb = (*function)(b);
  21. //Check the conditions of a root in the given interval
  22. if (a < b) {
  23. if (fa * fb < 0) {
  24. while (error > tolerance) {
  25. step++;
  26.  
  27. x = (a + b) / 2.0;
  28. f = (*function)(x);
  29.  
  30. if (f == 0) {
  31. cout << "Root found in x = " << x;
  32. return x;
  33. } else if (f * fa > 0) {
  34. a = x;
  35. } else if (f * fa < 0) {
  36. b = x;
  37. }
  38. error = (b - a) / pow(2.0, (double) step + 1);
  39. }
  40. cout << "Root found in x = " << x;
  41. return x;
  42. } else {
  43. cout << "There not exist a root in that interval." << endl;
  44. return -1;
  45. }
  46. } else {
  47. cout << "Mandatory \"a < b\", verify." << endl;
  48. return -1;
  49. }
  50. }
  51.  
  52. int main(int argc, char *argv[]){
  53. bisectionMethod(functionA, -3.0, 3.0, 10.0e-7);
  54. }
Success #stdin #stdout 0.02s 2680KB
stdin
Standard input is empty
stdout
Root found in x = 0.354492