二分法实现中的意外C行为

时间:2017-11-15 19:18:35

标签: c algorithm implementation terminate

我试图在C中实现Bolzano的Bisection方法,虽然该算法似乎有效,但它在4步后意外终止 并且第4步似乎增加了错误"和" divid"而不是让它不断减少。我试图保持代码尽可能简单,所以请不要在main等中使用指针/引用/数组/参数。

#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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在使用全局

int counter = 0;

控制函数bolzano中从不重置的操作。

请在bolzano

的开头添加此行
counter = 0;