Wednesday, 17 December 2014

Pin It

Widgets

Find root using False Position Method


#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(F(c)) > ERROR && iter < MAX_ITER);
    return c;
}

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

No comments: