0
votes

Having troubles exiting the while loop once the correct root has been found (value of r3 == 0). Should I be using a break somewhere, if so - where?

I have already tried playing around with the conditional for the if, else if and else statements. Tried placing the break; in different places but couldn't have it in such a way that I still received correct output (mostly it was breaking after the first iteration)

float fun(float t);
float fun(float t)
{
    double result; 
    result = (cos(t) - t); //my function
    return result; 
}

void main()
{
    float a; float b; float error; float root;
    scanf("%f %f %f", &a, &b, &error); //scanning for range of bisection and maximum allowed error
int i = 0; 

if (fun(a) == 0)
{
    root = a; 
    printf("The root is : %f", a);
}
else if (fun(b) == 0)
{
    root = b; 
    printf("The root is : %f", b);
}
else 
{
    while (i < 100)
    {
        float r1 = fun(a);
        float r2 = fun(b);
        root = (a+b)/2.0; 
        float r3 = fun(root); 
        printf("The root after %d iteration is %f\n",i,root);
        if(r1*r3 < 0 && r3 != 0) //intermediate value theorem
        {
            b = root;
        }
        else if(r3*r2 < 0 && r3 != 0) //intermediate value theorem
            {
                a = root;
            }
        i++;
        int *p = &i; //not necessary at this moment
    }
}
printf("The approximation to the root is %f",root);

The expected result is that the program should end at the first time that r3 == 0 since that would been that the found root using the bisection method is correct. Therefore, the last iteration should be the one with the correct final value for the root...

1

1 Answers

1
votes

First thing first, a condition r1 * r3 < 0 implies that r3 != 0 (if r3 == 0 the product is also 0); no need to test it.

Second, floats are very unlikely to be equal to anything, including 0. You should run a loop as long as you are not satisfied with the result. An error parameter is there for a reason.

Third, an unfortunate choice of a and b may never yield you a result: if fun(a), fun(b), fun((a+b)/2) all have the same sign, neither a nor b ever changes.

That said, the correct code should look like

    if (fun(a) * fun(b) > 0) {
        bail_out("Root may not exist\n");
    }

    while (b - a > error) /* see note below */ {
        mid = a + (b - a)/2;
        if (fun(a) * fun(mid) > 0) {
            a = mid;
        } else {
            b = mid;
        }
    }

Note: The condition above depends on the semantics of error. In certain circumstances (abs(fun(mid)) > error) may be preferable.