Computer Scientists are Pretty Pessimistic

Tuesday 28 February 2017

Bisection Method

#include <stdio.h>
#include <math.h>
double f(double x)
{
    return pow(x,2)-4*x-10; //Given equation may will be changed
}
int main()
{
    float x1,x2,x0,E;
    printf("Enter interval: ");
    scanf("%f %f",&x1,&x2);
    printf("Enter the tolerance value: ");
    scanf("%f",&E);
    if(f(x1)*f(x2)>=0)
    {
        printf("Incorrect Interval\n");
        return 0;
    }
    x0 = (x1+x2)/2;
    if(f(x0)==0)
    {
        printf("Root is: %.2lf\n",x0);
        return 0;
    }
    do
    {
        x0 = (x1+x2)/2;
        if(f(x1)*f(x0)<0)
        {
            x2 = x0;
        }
        else
        {
            x1 = x0;
        }
    }while(fabs((x2-x1)/x2)>E);
    printf("Root is: %.2f\n",(x1+x2)/2);
    return 0;
}
//Reference : Nemerical Methods by E Balagurusamy (2016-2017) pages (131 -138)

No comments:

Post a Comment