I am trying to implement a Bisection Root Finding Algorithm from scratch, and the equation I am passing it is x^2 - 42 = 0. My code keeps giving the output "The root of 42 is 0 within an error of 1e-05. ", meaning that the recursion stack of my bisection algo keeps returning 0 for some reason. The code is below:
#include <iostream>
#include <cmath>
using namespace std;
class Bisection
{
public:
double a;
double b;
double c;
double epsilon;
void set_values(double, double, double);
double f(double x)
{
return x*x - 42;
}
double solve(double a, double b, double epsilon)
{
c = (a+b)/2.0;
if(abs(f(c)) < epsilon)
{
return c;
}
else
{
if (f(a) * f(c) < 0.0)
{
b = c;
solve(a, b, epsilon);
}
else if (f(c) * f(b) < 0.0)
{
a = c;
solve(a, b, epsilon);
}
}
return 0;
}
};
void Bisection::set_values(double left, double right, double error)
{
a = left;
b = right;
epsilon = error;
}
int main()
{
Bisection myObj;
myObj.set_values(0.0, 10.0, 0.00001);
//cout << myObj.f(7);
cout << "The root of 42 is " << myObj.solve(myObj.a, myObj.b, myObj.epsilon) << " within an error of " << myObj.epsilon << ".";
return 0;
}
I had to include the "return 0;" line because my compiler was throwing back "non-void function does not return a value in all control paths" without it. How can I change my code to include a return value for all recursion paths but still yield the right answer? Is there an error in my fundamental design of the algorithm, or is it a simple fix?
Other problems with the code aside, you need to actually do something with the result of solve
. Usually this means return
ing the result from solve
directly until you reach the base case and return that:
double solve(double a, double b, double epsilon)
{
c = (a+b)/2.0;
if(abs(f(c)) < epsilon)
{
return c; //this is your base case
}
else
{
if (f(a) * f(c) < 0.0)
{
b = c;
return solve(a, b, epsilon);
}
else if (f(c) * f(b) < 0.0)
{
a = c;
return solve(a, b, epsilon);
}
}
}