Bisection Method

From CodeCodex

Revision as of 19:33, 27 March 2012 by Nostromo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

/* 
 * File:   main.cpp
 * Author: Bangonkali (bangonkali@gmail.com)
 *
 * Created on March 27, 2012, 9:23 PM
 * 
 * Information: A more in depth discussion on the algorithm
 * is taken from this book http://j.mp/GWBfba 
 */

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

/*
 * 
 */

double f(double x = 0) {
    // this is the function to find the root of
    // f(x) = (x+2)(x+2)(x+2); roots = -2;
    return (x*x*x) + (6*x*x) + (12*x) + 8;
}

/*
 * Get the number of iterations. More details are discussed
 * on this great book http://j.mp/GWBfba (page 3).
 */
int i(double a, double b, double tolerance) {
    return round(log2((abs(b-2))/tolerance));
}

int main(int argc, char** argv) {
    double a = 1e11; // initial guess a
    double b = -1e11; // initial guess b
    
    double c = 0; // root approximation
    double y = 0; // temporary holder (optimization)
    
    int iterations = i(a,b,1e-12); // get the num of iterations
    cout << "iterations: " << iterations << endl;
    
    for (int i = 0; i < iterations; i++) {
        c = (a + b) / 2; // get the root approximation
        cout << i << ":\nc = " << c << endl;
        
        y = f(c);
        cout << "y = " << c << endl;
        
        if (y < 0) {
            b = c;
            cout << "b = " << c << endl;
        } else if (y > 0) {
            a = c;
            cout << "a = " << c << endl;
        } else {
            break;
        }
    }
    
    cout << "root: " << c;
    
    return 0;
}