Alex
Alex

Reputation: 23

Unexpected C behavior in bisection method implementation

I'm trying to implement Bolzano's Bisection method in C, and while the algorithm appears to work, it terminates unexpectedly at around 4 steps and the 4th step appears to increase the "err" and "divid" rather than have it continuously decrease. I'm trying to keep the code as simple as possible so no pointer/references/arrays/arguments in main etc please.

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
//#define delta 0.00000000005
//#define epsilon 0.000000000005
//#define root1 1
//#define root2 -1
//#define maxit 7000

void bolzano(double a,double b, float root);
double function(double x);

int counter = 0;
//double err_global;//eps = 0.5e-6;
double maxit = 300;
double epsilon = 0.5E-6;
double delta = 0.5E-10;
int root1 = 1;
int root2 = -1;

int main(void){
    double a,b;
    printf("Eisagete tis times toy diastimatos [a,b]:  ");
    scanf("%lf%lf",&a,&b);
    printf("[a,b] = [%lf \\,%lf]\n",a, b);
    printf("                   ksi = %d\n", root1);
    printf("                            n   Xn   En   En+1/En");
    bolzano(a,b,root1);
    system("pause");
    printf("[a,b] = [%lf \\, %lf]\n",a, b);
    printf("                   ksi = %d", root2);
    bolzano(a,b,root2);
    system("pause");
    return 0;
}


double function(double x){
    return pow(x-1,3) * (x+1);
}


void bolzano(double a, double b, float root){
    double c,err,divit,err_global;
    while(b - a > epsilon && counter < maxit){
        //system("pause");
        c = (a + b)/2;
        err = fabs(c - root);
        if(counter == 0 ){
            err_global = err;
            printf("                           %d   %lf   %lf      \n", counter, c, err);
            counter++;
                if(function(a) * function(c) < 0){
                    b = c;
                    continue;
                }
                else{
                    a = c;
                    continue;
                }
        }
        divit = err/err_global;
        printf("                   ");
        printf("                           %d   %lf   %lf       %lf\n",counter, c ,err, divit);
        err_global = err;
        if(fabs(function(c)) < delta){
              break;
        }
        else if(function(a) * function(c) < 0){
            counter++;
            b = c;
            //continue;
        }
        else{
            counter++;
            a = c;
            //continue;
        }
    }
}

Upvotes: 1

Views: 96

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

You are using the global

int counter = 0;

to control the operations in function bolzano which is never reset.

Please add this line at the start of bolzano

counter = 0;

Upvotes: 1

Related Questions