-2

I'm working on a program to program the bisection method: https://www.calculushowto.com/bisection-method/

I know there's questions similar to this one but I want to see if my own one works.

double func(double x) {
    return x * x - 3 * x - 1;
}
    
double bisect(double (*f)(double), double a, double b, double e) {
    double mid = (a + b) / 2;
    while (abs(mid) > e) {
        if (f(mid) < 0) {
            mid = a;
        } else {
            mid = b;
        }
    }
      
    return mid;       
}

func() is the function I'm using to test the bisection method. In the other function, a is the left point, b is the right point and e is the error bound.

Any mistakes that I didn't catch?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Athhhelon
  • 3
  • 1
  • 4
    Is there something you think is wrong? Or you are just looking for a code review? (if the latter, maybe try on [codereview](https://codereview.stackexchange.com) – Alex Feb 02 '21 at 05:19
  • It may look like bisection at first sight, but I very much doubt it is. And that's not how the error bound works either. [Use a debugger to step through the program and understand what is going on and compare that with your expectations.](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Feb 02 '21 at 08:03

1 Answers1

1

There are multiple issues with the posted implementation, many of them could be easily addressed if the function were tested in a complete program.

  • The midpoint is calculated only once, at the beginning. Unless this was meant to be a recursive function, it should be updated inside the loop. To be nitpicking, the evaluation itself could be done differently, by first calculating a width = right - left and then mid = left + width / 2.0.

  • The termination condition is wrong, it should compare the width of the current interval with the limit or even the absolute value of f(mid) with a chosen minimal bound, not the value of mid.

  • Inside the loop, the value of mid is changed according to the signness of f(mid), but it should be the opposite: either the left bound or the right bound should be assigned to the value mid. The assumption that the function is ascending should be also somehow documented.

  • The function returns mid unconditionally, but either abs(f(a)) or abs(f(b)) could be less than abs(f(mid)).

Bob__
  • 12,361
  • 3
  • 28
  • 42