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

double bisection(double left, double right);

// The objective function
double f(double x)
{
  return( exp(x) - 3*x*x + 2*x );
}


int main()
{
  double a=-1.0, b=3.0, c;

  c = bisection(a,b);

  std::cout << "The maximum of the function between "
       << a << " and " << b << " is at "
	    << std::setprecision(10) << c << std::endl;

  return(0);
}


// FUNCTION: bsection
// ARGUMENTS: (double) a and (double) b
// RETURNS: (double) c, the point where the function f,
//    defined above, achieves its max.
double bisection(double a, double b)
{
  double c = (a+b)/2.0;
  while ( (b-a) > 1e-6)
    {
      c = (a+b)/2.0;
        double l = (a+c)/2.0, r=(c+b)/2.0;

        if ( (f(c) > f(l)) && (f(c) > f(r)) )
        {
            a=l;
            b=r;
        }
        else if ( f(l) > f(r) )
            b=c;
        else
            a=c;
    }
    return(c);
}
