Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top