Hey guys,
I'm working on a problem where I need to use the direct-search method to find the intervals of the roots and bisection method to find the roots of the following equation x^3-3.5x^2+3.48x-0.85. Here is the code I have so far, the problem I'm getting is when the code is ran it only spits out one of the roots and I have no clue how to get it to loop back to solve for the other three. Any help would be appricated.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
double f(double x);
double direct(double a, double b, int n);
double bisection(double xa, double xb, double eps);
int main()
{
double x0 = 0.0, xn = 2.5, eps = 0.01;
int n = 10;
printf( "Using the direct-search method the intervals of the roots are: %f\n", direct(x0, xn, n) );
printf( "Using the bisection method the roots are: %f\n", bisection(x0, xn, eps) );
return 0;
}
double f(double x)
{
double y;
y = (x*x*x)-3.5*(x*x)+3.48*x-0.85;
return y;
}
double direct(double a, double b, int n)
{
int i;
double dx, x, f1, f2;
dx = (b - a) / n;
f1 = f(a);
for (i = 0; i <= n; i++) {
x = a + dx * i;
f2 = f(x);
if (f1 * f2 <= 0) break;
f1 = f2;
}
return x-dx/2;
}
double bisection(double xa, double xb, double eps)
{
double xm, fa, fm;
fa = f(xa);
while (xb - xa > eps) {
xm = (xa + xb) / 2;
fm = f(xm);
if (fm == 0.0) break;
else if (fa*fm > 0) {
xa = xm;
fa = fm;
}
else {
xb = xm;
}
}
return xm;
}