Numerical Methods: Bisection Method


/ Published in: C++
Save to your folder(s)

A more in depth discussion on the algorithm is taken from this book http://j.mp/GWBfba.


Copy this code and paste it in your HTML
  1. /*
  2.  * File: main.cpp
  3.  * Author: Bangonkali ([email protected])
  4.  *
  5.  * Created on March 27, 2012, 9:23 PM
  6.  *
  7.  * Information: A more in depth discussion on the algorithm
  8.  * is taken from this book http://j.mp/GWBfba
  9.  */
  10.  
  11. #include <cstdlib>
  12. #include <iostream>
  13. #include <cmath>
  14. using namespace std;
  15.  
  16. /*
  17.  *
  18.  */
  19.  
  20. double f(double x = 0) {
  21. // this is the function to find the root of
  22. // f(x) = (x+2)(x+2)(x+2); roots = -2;
  23. return (x*x*x) + (6*x*x) + (12*x) + 8;
  24. }
  25.  
  26. /*
  27.  * Get the number of iterations. More details are discussed
  28.  * on this great book http://j.mp/GWBfba (page 3).
  29.  */
  30. int i(double a, double b, double tolerance) {
  31. return round(log2((abs(b-2))/tolerance));
  32. }
  33.  
  34. int main(int argc, char** argv) {
  35. double a = 1e11; // initial guess a
  36. double b = -1e11; // initial guess b
  37.  
  38. double c = 0; // root approximation
  39. double y = 0; // temporary holder (optimization)
  40.  
  41. int iterations = i(a,b,1e-12); // get the num of iterations
  42. cout << "iterations: " << iterations << endl;
  43.  
  44. for (int i = 0; i < iterations; i++) {
  45. c = (a + b) / 2; // get the root approximation
  46. cout << i << ":\nc = " << c << endl;
  47.  
  48. y = f(c);
  49. cout << "y = " << c << endl;
  50.  
  51. if (y < 0) {
  52. b = c;
  53. cout << "b = " << c << endl;
  54. } else if (y > 0) {
  55. a = c;
  56. cout << "a = " << c << endl;
  57. } else {
  58. break;
  59. }
  60. }
  61.  
  62. cout << "root: " << c;
  63.  
  64. return 0;
  65. }

URL: http://j.mp/GWBfba

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.