Technupe
Technupe

Reputation: 4961

Please help me find out why i am in an infinite loop?

this is a bisection root method

double p1::root(double (*pf)(double k), int a, int b, double e) {

  // void nrerror(char error_text[]);

  double left = (double)a;
  double right = (double)b;
  double midpoint;

  do
  {
      midpoint = ((right+left)/2);

      if(pf(left) *pf(midpoint) <0){
          right = midpoint;
      }
      else if(pf(right) * pf(midpoint) <0){
          left = midpoint;
      }
      else{
          break;
      }
  }while(abs(right-left) >2*e && abs(left-right)>e);

  return midpoint;
}

Upvotes: 2

Views: 144

Answers (3)

Rushil Paul
Rushil Paul

Reputation: 2048

Compile the program giving a -g switch for debugging and run it by gdb. That way you will know for what values is your do-while condition becoming true erroneously.

Upvotes: 0

sehe
sehe

Reputation: 392833

I see multiple exclusive relationals <, < and >

I expect at least one of them to be inclusive (>= or <=)

This is a good general rule of thumb (exceptions may occur, e.g. with intermediate increments of the compared values... so you need to stay awake, which is the first goot rule of thumb)

Upvotes: 2

ColWhi
ColWhi

Reputation: 1077

I would suggest putting some printfs in an doing some tracing of where you are.

Upvotes: 1

Related Questions