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;
}
Member Avatar for iamthwee

There should be three solutions:

0.363
1.223
1.913

So you have to select starting points from 0-2.

Which would be defined here:

double x0 = 0.0, xn = 2.5, eps = 0.01;

For example to get the root 1.22

x0 could be 1.0 and xn could be 1.3

Bear in mind not all equations have real solutions, as in some could have complex(imaginary) solutions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.