Bisection Method help

I am attempting to use the following code to solve per the Bisection Method for the roots of the following function:

x^3-0.165*x^2+0.0003993 using episilon 10-7 and Limits 0.04 and 0.15

I haven't taken C++, so I am fumbling in the dark trying to find info on the web. I think I understand the gist of it..any insight would be appreciated...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<fstream>
#include <iostream>
#include<cmath>
#include<iomanip>

using namespace std;

// Prototypes of functions used
void bisection(double ,double, double, double,
			   double, double, double&, int& );
double fx(double, double, double, double, double);
const double tol=0.0000001; // tolerance for convergence
const int max_iter=1000;  // Number of maximum iterations allowed
// main program

int main(void)
{
	int iteration;               // number of iterations
	double a, b, c, d;	     // Constants in f(x)
	float xl, xr;    	     // Starting points for x
	double root;                 // root found by Method
	cout<<"Enter a, b, c, and d"<<endl<<"separated by a space ";
	cin>>a>>b>>c>>d;
	cout<<"Enter two initial values for x ";
	cin>>xl>>xr;
	bisection(a, b, c, d, xl, xr, root, iteration);// call Method
// Output
	cout<<"The root is = "<<root<<endl;
	cout<<"The number of iterations was = "<<iteration<<endl;
	cout<<"The value of f at the root = "<<fx(a,b,c,d,root)<<endl;
}
// Function Bisection starts here
// Recieves a, b, c, d and x0 values from main program
// Sends root found and the iteration number
void bisection(double a,double b, double c, double d, 
			double xl, double xr, double& root, int& iteration)
{
	double xm;     // local variables
	iteration=0;   // setting number of iterations to zero
do
{
	xm=(xl+xr)/2.;
	++iteration;
	if(fx(a,b,c,d,xl)*fx(a,b,c,d,xm)<0) xr=xm;
	else xl=xm;
	cout<<"xm = "<<xm<<endl;
}  
while ((fabs(fx(a,b,c,d,xm)) >= tol )&& (iteration < max_iter));
	root=xm;  
}
// fx, calculates ax^3+bx^2+cx+d
double fx(double a, double b, double c, double d, double x)
{
	return a*pow(x,3)+b*pow(x,2)+c*x+d;
}
In the while loop check, you are checking to see if the value of f(x) is >= tol but that is not what tol is. TOL is how close you want to get the calculated root (the x value) to the real root. What you are checking is if the value of f(x) or y < TOL. The TOL check should be (xr-xl)/2 < TOL then stop. The f(x) should check if it equals 0 then stop because you found the root.

 
while((xr-xl)/2.0 >= tol && fx(a,b,c,d,xm) != 0.0 && iteration < max_iter);


What do you think?

Ref: http://en.wikipedia.org/wiki/Bisection_method
Last edited on
Topic archived. No new replies allowed.