Sunday 22 March 2015

To find the root of a equation using Secant Method Using C

# include <stdio.h>
# include <conio.h>
# include <math.h>

# define EPS 0.000001
# define MAXIT 50
# define F(x) (x) * (x) * (x) - 2 * (x) - 5

void main()
{
float a, b, root, x1, x2 ;
int count, status ;
clrscr() ;
printf("Input two starting points : ") ;
scanf("%f %f", &a, &b) ;
sec(&a, &b, &x1, &x2, &root, &count, &status) ;
if(status == 1)
{
printf("\nDivision by zero") ;
printf("\nLast x1 = %f", x1) ;
printf("\nLast x2 = %f", x2) ;
printf("\nNo. of iterations = %d", count) ;
}
else if(status == 2)
{
printf("\nNo convergence in %d iterations", MAXIT) ;
}
else
{
printf("\nRoot = %f", root) ;
printf("\n\nFunction value at root = %f", F(root)) ;
printf("\n\nNo. of iterations = %d", count) ;
}
getch() ;
}
sec(float *a, float *b, float *x1, float *x2, float *root,
int *count, int *status)
{
float x3, f1, f2, error ;
*x1 = *a ;
*x2 = *b ;
f1 = F(*a) ;
f2 = F(*b) ;
*count = 1 ;
begin :
if(fabs(f1 - f2) <= 1.E-10)
{
*status = 1 ;
return ;
}
x3 = *x2 - f2 * (*x2 - *x1) / (f2 - f1) ;
error = fabs((x3 - *x2) / x3) ;
if(error > EPS)
{
if(*count == MAXIT)
{
*status = 2 ;
return ;
}
else
{
*x1 = *x2 ;
}
*x2 = x3 ;
f1 = f2 ;
f2 = F(x3) ;
*count = *count + 1 ;
goto begin ;
}
else
{
*root = x3 ;
*status = 3 ;
return ;
}
}

RUN 1 :
~~~~~~~
Input two starting points : 2 3
Root = 2.094552
Function value at root = 0.000001
No. of iterations = 6

No comments:

Post a Comment