The program has to look for a root in an interval [a,b]
. The root should be declared with a certain accuracy eps
. I.e it should look for a part-interval in [a,b]
, which has the length of eps
.
The bisection algorithm should be:
- Save the interval boundaries
- Look if
[a,b]
has a root. (original given interval) - look if
a-b < eps
. If yes, part-interval found. - If no, divide
[a,b]
in half and continue with point 2. etc.
(We can assume that there is already a root in the given original interval [a,b]
)
I've tested it with following functions:
log x + 2
x*x*x
-3.*x*x + x + 2.
Are there any improvements possible or did I make a big mistake?
Bisection.cpp
#include "Bisection.hpp"
#include <cmath>
using namespace std;
void bisection(std::vector<double>& interval, double eps) {
double a;
double b;
double c;
a = interval[0];
b = interval[1];
if (b - a < eps) // interval already 'found'
{
return;
}
do
{
c = (a + b) / 2.0;
if (f(c) == 0)
{
a = c;
b = c;
}
else
{
if (f(a) * f(c) > 0)
{
a = c;
}
else
{
b = c;
}
}
} while (f(c) != 0 || b - a > eps);
/*found part-interval with the length of < eps*/
interval[0] = a;
interval[1] = b;
}
while (f(c) != 0 || b - a > eps)
rather thanwhile (f(c) != 0 && b - a > eps)
? \$\endgroup\$