fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. #include <vector>
  5. #include <utility>
  6.  
  7. #define MINX (-20.0f)
  8. //MAXX Happens to be an upper bound for all zeroes of the function...
  9. #define MAXX (1.0f)
  10. #define NUM_INTERVALS (1000000)
  11. #define NUM_BISECTION_ITERATIONS (30)
  12.  
  13. using namespace std;
  14.  
  15. double f(double x){
  16. return 5 * x * exp(-x) * cos(x) + 1;
  17. }
  18.  
  19. //Used for Newton's method, if so desired... but that isn't used here.
  20. double df(double x){
  21. return -5 * exp(-x)*x*sin(x) + 5 * exp(-x) * x * sin(x) - 5 * exp(-x) * x * cos(x);
  22.  
  23. }
  24.  
  25. double bisection_method(double x0, double x1){
  26. for (unsigned int i = 0; i < NUM_BISECTION_ITERATIONS; i++){
  27. double midpoint = 0.5*x0 + 0.5*x1;
  28. f(x0) * f(midpoint) < 0 ? x1 = midpoint : x0 = midpoint;
  29. }
  30. return 0.5*x0 + 0.5*x1;
  31. }
  32.  
  33. int main(int argc, char** argv){
  34. vector<pair<double, double>> relevant_intervals;
  35. for (unsigned int i = 0; i < NUM_INTERVALS - 1; i++){
  36. double x0 = MINX + (MAXX - MINX) / NUM_INTERVALS * (i);
  37. double x1 = MINX + (MAXX - MINX) / NUM_INTERVALS * (i + 1);
  38. if (f(x0) * f(x1) < 0)
  39. relevant_intervals.push_back(make_pair(x0, x1));
  40. }
  41. cout << fixed << setprecision(20);
  42. for (const auto & x : relevant_intervals){
  43. cout << "One solution is approximately " << bisection_method(x.first, x.second) << endl;
  44. }
  45. }
Success #stdin #stdout 0.77s 3432KB
stdin
Standard input is empty
stdout
One solution is approximately -17.27875959510648584683
One solution is approximately -14.13716693089815734652
One solution is approximately -10.99557459270114279093
One solution is approximately -7.85397174835090350342
One solution is approximately -4.71277006702168055341
One solution is approximately -1.54309268258421017350
One solution is approximately -0.17105185875076850399