Bisection method

A simple C++ example of the Bisection method for finding the root of a function

bsm.h


/*
* bsm.h
*
* Created on: Sep 1, 2016
* Author: christos
*/

#ifndef BSM_H_
#define BSM_H_

#include <iostream>
#include <math.h>
#include <stdlib.h>

using namespace std;

const double delta=1.0e-8;
const double epsilon=1.0e-9;
double bsm(double (*f)(double),double a,double b,double delta,double epsilon);
double f0(double x);
double f1(double x);
double f2(double x);

#endif /* BSM_H_ */

bsm.cpp


/*
* bsm.cpp
*
* Created on: Sep 1, 2016
* Author: christos
*/
#include "bsm.h"

double bsm(double (*f)(double), double a, double b, double delta, double epsilon){

double c=(a+b)/2.0;

if (fabs(b-a)*0.5<delta||fabs(f(c))<epsilon) return c;

(f(a)*f(c)<0)? b=c:a=c;
return bsm(f,a,b,delta,epsilon);

}
double f0(double x){

if (x) return 1.0/pow(x,2) -pow(2,x);
else {

cout<<"Division with zero occured in function f0";
exit(1);
}

}
double f1(double x){

return pow(2,-4*x)+exp(2*x)+2*cos(x)-12;
}
double f2(double x){
double temp=pow(x,3)-pow(x,2)+18*x-2;

if (temp) return (2*pow(x,4)+4*pow(x,3)+12*x+5)/temp;

else {

cout<<"Divisoion by zero occured in f2";
exit(1);
}
}

 

main.cpp


//============================================================================
// Name : bisectionMethod.cpp
// Author : chd
// Version :
// Copyright :
// Description : Bisection method
//============================================================================
#include "bsm.h"
int main() {
double rootf0=bsm(f0,1.0e-3,1,delta,epsilon);
double rootf1=bsm(f1,1,3,delta,epsilon);
double rootf2=bsm(f2,0,4,delta,epsilon);
cout<<"The root of f0 is:"<<rootf0<<"\n";
cout<<"The residual is"<<f0(rootf0)<<"\n";

cout<<"The root of f1 is:"<<rootf1<<"\n";
cout<<"The residual is"<<f1(rootf1)<<"\n";
cout<<"The root of f2 is:"<<rootf2<<"\n";
cout<<"The residual is"<<f2(rootf2)<<"\n";
return 0;
}