Guys..Can anyone help me to explain what really happened in the while loop and both of the if else loop that makes this coding can find the root using bisection method.Thank you...
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double f( double);
int main ( int argc, char *argv[])
{
int kmax;
double a,b,eps;
cout <<" Input a,b, eps, kmax\n ";
cin>> a >> b >> eps >> kmax;//use big kmax , eps 0.5e-6
cout << " The input data are\n";
cout << "a= "<< a << "b= "<< b;
cout << "eps= "<< eps << "kmax= "<< kmax<< endl;
cout<< " The results are\n";
cout<< "k a b x f(x)\n";
int k=1;
double x=0.5*(a+b );//first bisection
while (( k<=kmax) && (fabs(f(x))>eps)) // <-- this has changed
{
cout << setw(2)<< k << setprecision(5)<< fixed<< setw(8)<< a<< setw(8)<< b << setprecision(6) <<setw(10)<<x<< setw(12)<<f(x) << endl;
if (f(x) <0)
a=x;
else
b=x;
x= 0.5*(a+b);
k++;
}
if ( (k>kmax) || ( fabs(f(x)) > eps ) )
cout << "no convergence";
else
cout << " \nThe root = "<< x<< endl;
return 0;
}
double f(double x){
return (tan(x)-x);
}