Hey everybody.. I have some problem here.
This is the question: Find a root of the equation on the interval [4,5] by using the bisection method. What happens on the interval [ 1 , 2] ?

I wrote the code and everything seems fine with the interval [4,5] but for interval [1,2] the cout supposed to be no convergence but the code cout the root. Please help me. Thank you in advance.:)

#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	x  f(x)		a	 b\n";

int k=1;

double x=0.5*(a+b);//first bisection

while (( k<=kmax) && ((b-a)>eps))
{
	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) 
cout << "no convergence";
else
cout << " \nThe root = "<< x<< endl;
return 0;
}
double f(double x){
  return (tan(x)-x);
  }

Your algorithm is missing a piece I think it should be

if (f(x)*f(a) <0)  //sign change between a and x, dump right half
		b=x;
	else if(f(x)*f(b)<0) //sign change between b and x dump left 
		a=x;
	else       //no change no root
		break;//we got it

That being said, I only was able to get no convergence for the [1,2] interval using a super tiny epsilon (one which probably borders on the limits for the machine so may not be valid). If you plot that function you can kind of see what is going on.

One minor detail your labels across the top are in the wrong order it should be k a b x f(x). That was really confusing at first.

hi..thank you for the insights.. but the problem is when i input kmax=100 it will be back to the same problem....

i've corrected the wrong order.thx again..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.