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
|
#include<fstream.h>
#include<math.h>
#include<iomanip.h>
// 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.0001; // tolerance for convergence
const int max_iter=100; // Number of maximum iterations allowed
// main program
void main()
{
int iteration; // number of iterations
double a, b, c, d; // Constants in f(x)
double 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;
}
|