C : bisection method


#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#define E 0.00001
#define f(x) x*x-4*x-10
int main()
{
float x0,x1,y0,y1,x2,y2;
int i=0;
printf("enter the initial guess\n\n");
scanf("%f%f", &x0,&x1);
y0=f(x0);
y1=f(x1);
if((y0*y1)>0)
{
printf("initial guess are not suitable \n\n");
getch();
exit(0);
}
printf("iter\tx0\tf(x0)\tx1\tf(x1)\tx2\tf(x2)\n");
while(fabs((x1-x0)/x1)>E)
{
x2=(x0+x1)/2;
y2=f(x2);
i=i+1;
printf("%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t\n",i,x0,y0,x1,y1,x2,y2);
if(y0*y2>0)
x0=x2;
else
x1=x2;
}
printf("number of iteration is %d\n",i);
printf("the root is %.2f",x2);
getch();
return(0);
}

No comments:

Post a Comment