Sunday 22 March 2015

Find the root of a equation using Bisection method Using C

# include <stdio.h>
# include <conio.h>
# include <math.h>
# define EPS 0.000001
# define F(x) (x) * (x) * (x) - 2 * (x) - 5
void main()
{
int s, count ;
float a, b, root ;
clrscr() ;
printf("Input starting values : ") ;
scanf("%f %f", &a, &b) ;
bim(&a, &b, &root, &s, &count) ;
if(s == 0)
{
printf("\nStarting points do not bracket any root.") ;
printf("\nCheck whether they bracket EVEN roots.") ;
}
else
{
printf("\nRoot = %f", root) ;
printf("\n\nF(root) = %f", F(root)) ;
printf("\n\nIterations = %d", count) ;
}
getch() ;
}
bim (float *a, float *b, float *root, int *s, int *count)
{
float x1, x2, x0, f0, f1, f2 ;
x1 = *a ;
x2 = *b ;
f1 = F(x1) ;
f2 = F(x2) ;
if(f1 * f2 > 0)
{
*s = 0 ;
return ;
}
else
{
*count = 0 ;
begin :
x0 = (x1 + x2) / 2.0 ;
f0 = F(x0) ;
if(f0 == 0)
{
*s = 1 ;
*root = x0 ;
return ;
}
if(f1 * f0 < 0)
{
x2 = x0 ;
}
else
{
x1 = x0 ;
f1 = f0 ;
}
if(fabs((x2 - x1) / x2) < EPS)
{
*s = 1 ;
*root = (x1 + x2) / 2.0 ;
return ;
}
else
{
*count = *count + 1 ;
goto begin ;
}
}
}

RUN 1 :
~~~~~~~
Input starting values : 2 3
Root = 2.094552
F(root) = 0.000006
Iterations = 18


No comments:

Post a Comment