Pages

Saturday 31 March 2018

Regula-Falsi Method in C/C++

PROGRAM :

//To write a C/C++ program to find roots of an equation using
//Regula-Falsi method.

#include<stdio.h>
#include<math.h>
float bisect(float a,float b);
float f(float x);
float f(float x)
{
float f;
f=cos(x)-x*exp(x);
return f;
}
float bisect(float a,float b)
{
float c=((b*f(a))-(a*f(b)))/(f(a)-f(b));
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 :0 1
Enter the no. of iterations required and Allowed error25
0.0001

Iteration no. 0 value of x is 0.314665
Iteration no. 1 value of x is 0.446728
Iteration no. 2 value of x is 0.494015
Iteration no. 3 value of x is 0.509946
Iteration no. 4 value of x is 0.515201
Iteration no. 5 value of x is 0.516922
Iteration no. 6 value of x is 0.517485
Iteration no. 7 value of x is 0.517668
Iteration no. 8 value of x is 0.517728

root is 0.517728