0
votes

I have a problem with bisection method (recursive implementation) that doesn't work. The program just crashes after entering a&b values ...

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define e 0.0001
#define dbg 1
using namespace std;
double f(double x){
    return x*x*x-x-2;
}
double bisection(double a,double b){
    double x1;
    x1=(b+a)/2;
    if(x1>e){
        if(f(b)*f(x1)<0)
        {
            a=x1;
        }
        else
        if(f(a)*f(x1)<0)
            b=x1;
        bisection(a,b);
        }
    return x1;
}
int main () {
    int a,b;
    double root;
    printf("a=");
    scanf("%d",&a);
    printf("b=");
    scanf("%d",&b);
    if(f(a)*f(b)<0){
        root=bisection(a,b);
        printf("root %g",root);
    }

    system("pause");
    return 0;
}

I have tried to display some debugging messages, but I couldn't figure it out.

1
What is this doing? return x*x*x-x-2; - Digital_Reality
Return the function ( X^3-x-2 ) - Marian Pavel
What is your question? "Figure out my error" isn't the point of SO. - Gene
A couple of place to look and think hard about: 1) x1>e. This is not what you want. And 2) bisection(a,b); You never use the return value! - Gene
how it should look like, I know I need to have an ε to compare with. - Marian Pavel

1 Answers

0
votes

As @Gene pointed out, you never use the result of the recursive call. Further, what you DO return is just the midpoint between a&b, which you don't need recursion to find. (Related?)

Note that, if the 2 ifs used to change either a or b for the recursive call both fail, then you make a recursive call w/ unchanged values of a & b ==> infinite recursion, a sure way to get a segfault.