Pages

Saturday, 31 March 2018

Bisection Method in C/C++

PROGRAM :

//To write a C/C++ program to find roots of a polynomial using
//bisection method.


#include<stdio.h>
#include<math.h>
float bisect(float a,float b);
float f(float x);
float f(float x)
{
float f;
f=pow(x,3)-4*x-9;
return f;
}
float bisect(float a,float b)
{
float c=(a+b)/2;
return c;
}
void main()
{
float a,b,x0,ae,x1;
int itr,maxitr;
printf("Enter a & b :");
scanf("%f%f",&a,&b);
if (f(a)*f(b)<0)
{
printf("Enter the no. of iterations required and Allowed error");
scanf("%d%f",&maxitr,&ae);
x0=bisect(a,b);
printf("Iteration no. 0 value of x is %f\n",x0);
for(itr=1;itr<=maxitr;itr++)
{
if (f(x0)*f(a)<0)
b=x0;
else a=x0;
x1=bisect(a,b);
printf("Iteration no. %d value of x is %f\n",itr,x1);
if ((fabs(x1-x0))<=ae)
{
printf("root is %f",x1);
break;
}
x0=x1;
}
if (itr==maxitr && fabs(x1-x0)>ae)
printf("Number of iterations is not sufficient");
}

}




OUTPUT :

Enter a & b :2 3
Enter the no. of iterations required and Allowed error25
0.00001
Iteration no. 0 value of x is 2.500000
Iteration no. 1 value of x is 2.750000
Iteration no. 2 value of x is 2.625000
Iteration no. 3 value of x is 2.687500
Iteration no. 4 value of x is 2.718750
Iteration no. 5 value of x is 2.703125
Iteration no. 6 value of x is 2.710938
Iteration no. 7 value of x is 2.707031
Iteration no. 8 value of x is 2.705078
Iteration no. 9 value of x is 2.706055
Iteration no. 10 value of x is 2.706543
Iteration no. 11 value of x is 2.706299
Iteration no. 12 value of x is 2.706421
Iteration no. 13 value of x is 2.706482
Iteration no. 14 value of x is 2.706512
Iteration no. 15 value of x is 2.706528
Iteration no. 16 value of x is 2.706535

root is 2.706535