The following function returns zero in the interval (a,b) of the function: f(x)=5*sin(x)*log(x) with precision eps. I don't understand the else part where we have the condition if(f(a)*f(x)<0. I do understand that if we have interval (a,b) and f(a)*f(b)<0 it means zero of a math function is in that interval, but I don't understand why using binary search we reduced the right side for that condition.

float zero(float a, float b, float eps){

    float x = a + (b-a)/2;

    float val = 5*sin(x)*log(x);
    if(fabs(val) < eps){
        return x;
    }else{

        float left = 5*sin(a)*log(a);
        if(left*val < 0)
            return zero(a, x, eps);
        else
            return zero(x, b, eps);

    }
}

for the input: 0.9 2 0.01 the output: 0.998828

1 Answers

2
Community On Best Solutions

You are using the bisection method to find the zeros (also called root). Using this method is like applying binary search again and again until the value is smaller than epsilon. Depending on the sign of the answer, we either continue with the left or right side of the section and refine this process until the value is small enough. Here is a detailed example of how this mathematically works.