Saturday, May 18, 2013

Newton-Raphson Method in C with source codes

Newton-Raphson method is a method for finding successively better roots (zeros) of a real valued function
x: f(x) = 0.

The algorithm can be implemented in C as follows:


#include<stdio.h>
#include<math.h>
#include<conio.h>
#define h pow(10,-6)
#define error pow(10,-6)
double f(double x)
{
 return(x*x-4);
}
double df(double x)
{
 return 2*x;
}
int main()
{
int iter=0,maxiter,i;
double x0,x1;
for( i=-5;i<=5;i++)
{
    printf("\n\t%d \t\t %6.2lf",i,f(i));
    if(f(i)*f(i-1)<=0)
      break;
}

 while(1){


        x0=i;
        printf("\nInitial approximation taken within given limits : %lf \n",x0);
        if (fabs(df(x0))==0)
        {
                printf("Denominator :(Derivative) zero !! choose another guess .\n");

        }
        else
               break;
 }
  while(1)
        {
                ++iter;
                x1=x0-f(x0)/df(x0);
                printf("\nx%d = %lf \tf(x%d) = %lf \n",iter,x1,iter,f(x1));
                if(fabs(x1-x0)< error||f(x1)<error)
                    break;
                x0=x1;
        }

printf("\n Root = %lf ",x1);
printf("\n No.of iterations = %d",iter);
printf("\n interval width = %lf",fabs(x1-x0));
getch();
return 0;
}


No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...