#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
float f(float x)
{
return(x*x*x*-4*x-9);
}
void bisect(float *x,float a,float b,int *itr)
{
*x=(a+b)/2;
++(*itr);
cout<<“Iteration no.”<<setw(3)<<*itr;
cout<<“X= ” <<setw(7)<<setprecision(5);
cout<<*x<<endl;
}
int main()
{
int itr=0,maxitr;
float x,a,b,aerr,x1;
cout<<“Enter the values of a, b, “;
cout<<“allowed error, maximum iteration”<<endl;
cin>>a>>b>>aerr>>maxitr;
cout<<fixed;
bisect(&x,a,b,&itr);
do
{
if(f(a)*f(x)<0)
b=x;
else
a=x;
bisect(&x1,a,b,&itr);
if(fabs(x1-x)<aerr)
{
cout<<"After "<<itr<<" iterations, root";
cout<<"="<<setw(6)<<setprecision(4);
cout<<x1<<endl;
return 0;
}
x=x1;
}while(itr < maxitr);
cout<<"Solution does not converge,";
cout<<"iterations not sufficient"<<endl;
return 1;
}
Output
Enter the values of a, b, allowed error, maximum iteration
3 2 0.0001 15
Iteration no. 1X= 2.50000
Iteration no. 2X= 2.25000
Iteration no. 3X= 2.12500
Iteration no. 4X= 2.06250
Iteration no. 5X= 2.03125
Iteration no. 6X= 2.01562
Iteration no. 7X= 2.00781
Iteration no. 8X= 2.00391
Iteration no. 9X= 2.00195
Iteration no. 10X= 2.00098
Iteration no. 11X= 2.00049
Iteration no. 12X= 2.00024
Iteration no. 13X= 2.00012
Iteration no. 14X= 2.00006
After 14 iterations, root=2.0001
