Navigation

Saturday, 28 February 2015

program for finding root using bisection method

 /*program for finding root using bisection method*/
#include<math.h>
#define f(x) x*x*x-2*x-5
void main()
{
    float x0,x1,e,x2,y0,y1,y2;
    int i;
    clrscr();
    printf("\n\n\t\tPROGRAM FOR FINDING ROOT USING BISECTION METHOD\n\n\n");
    printf("Enter the value of x0,x1,e\n");
    scanf("%f%f%f",&x0,&x1,&e);
    y0=f(x0);
    y1=f(x1);
    i=0;
    if((y1!=0)&&((y0/y1)>0))
    {
        printf("Starting values are not correct");
        printf("x0=%f,x1=%f,y0=%f",x0,x1,y0,y1);
        exit(0);
    }
    while(fabs((x1-x0)/x1)>e)
    {
        x2=(x0+x1)/2;
        y2=f(x2);
        i=i+1;
        if((y2!=0)&&((y0/y2)>0))
        {
            x0=x2;
            y0=y2;
        }
        else
        {
            x1=x2;
            y1=y2;
        }
        printf("x%d = %f\n",i,x2);
    }
    printf("Hence the root is %f\n\n",x2);
    printf("Total number of iterations are %d",i);
    getch();
}

No comments:

Post a Comment