Bisection

 #include<iostream>

#include<iomanip>

#include<math.h>

#define bisect(a,b) (a+b)/2

#define err 0.000001 

using namespace std;

float f(float x)

{

   return //Enter your equation

}

int main()

{

int i = 1,max;

float x,x1,a,b;

cout<<"Enter initial approximate root a: ";

cin>>a;

cout<<"Enter initial approximate root b: ";

cin>>b;

cout<<"Enter max number of iterations: ";

cin>>max;

cout<<setprecision(10)<<"Iteration\troot\n";

x=bisect(a,b);

while(i<max)

{

    cout<<i<<"\t\t"<<x<<endl;

    if(f(a)*f(x)<0)

    {

        b=x;

    }

    else

    {

        a=x;

    }

    x1 = bisect(a,b);

    i++;

    if(fabs(x1-x)<err)

    {

        cout<<"\nRoot after "<<i<<" iteration="<<setprecision(10)<<bisect(a,b)<<endl;

        return 0;

    }

    x= x1;

}

cout<<"\nSolution doesnot cover: "<<i<<" iteration not sufficient";

return 1;

}


0 Comments: