False position method has reached its maximum iteration limit MAX

I am trying to write a program to find the roots of a continuous function using the false position method. But I get the same value of c over and over again , and the same value is assigned to a , which causes the MAX_ITER limit to be reached. How can I avoid this? Am I using the algorithm incorrectly?

#include<stdio.h>
#include<math.h>

#define F(x) ((2*x)+1)
#define ERROR 0.00001
#define MAX_ITER 1000

float FalsePosition(float a, float b)
{   
    float c;
    int iter = 0;
    do
    {
        c = (b - F(b)) * (b - a) / (F(b) - F(a));

        printf("F(a): %f, F(b) : %f, F(c) : %f, a: %f, b : %f, c : %f\n", F(a), F(b), F(c), a, b, c);

        if((F(c) > 0 && F(a) > 0) || (F(c) < 0 && F(a) < 0))
        {
            a = c;
        }
        else
        {
            b=c;
        }

        iter++;
    }
    while(fabsf(a-b) > ERROR && iter < MAX_ITER);
    return a;
}

int main()
{
    float a = -2.5;
    float b = 2.5;

    printf("Finding root in the interval [%f, %f]\n", a, b);

    if((F(a)>0 && F(b)>0) || (F(a)<0 && F(b)<0))
    {
        printf("No root lie in the interval [%f, %f]", a, b);
    }
    else
    {
        printf("The root is : %f\n", FalsePosition(a, b));
    }

    return 0;
}

      

+3


source to share


1 answer


Your formula for c

is wrong, it should be

c = b - (f(b) * (b - a)) / (f(b) - f(a));

      

see here

To prevent reaching iterations MAX_ITER

, you can watch the change in c

something like



previousValue = c;
c = b - (f(b) * (b - a)) / (f(b) - f(a));

      

and then the while condition would be

while ((fabs(previousValue - c) > ERROR) && (iter < MAX_ITER));

      

you can initialize previousValue

before a

to start the loop. Finally, you must return c

not a

.

+3


source







All Articles