c programming
Newton Raphson Method process 1 C++
Newton Raphson Method
Newton Raphson Method |
C Programming:Dev c++
/**********************************************************
**************NEWTON RAPHSON METHOD****************
**********************************************************/
/*Using Newton’s method, find the root of 3*x+sin(x)-exp(x).*/
#include<stdio.h>
#include<math.h>
double f(double x)
{
return 3*x+sin(x)-exp(x);
}
double df(double x)
{
return 3-cos(x)-exp(x);
}
main()
{
double x,eps,x1;
int maxSteps;
printf("Enter the initial guess:\n");
scanf("%lf",&x1);
printf("Enter the desired accuracy:\n");
scanf("%lf",&eps);
printf("Enter the max. number of steps:\n");
scanf("%d",&maxSteps);
int iter=1;
printf("________________________________________________________________________\n");
printf("x\tf(x)\t\tf'(x)\t\tx1\t\t|x-x1|\t\tf(x1)\n");
printf("________________________________________________________________________\n");
do{
x=x1;
if(fabs(df(x))>=0.000000001&&df(x)!=NAN){
x1=x-f(x)/df(x);
printf("%d.\t%lf\t%lf\t%lf\t%lf\t%lf\n",iter,f(x),df(x),x1,fabs(x-x1),f(x1));
iter++;
}
else{
printf("Sorry! The slope is 0 for one of the iterations.\n NR Method failed.\n");
return 0;
}
}
while(fabs(x-x1)>=eps&&iter<=maxSteps);
printf("________________________________________________________________________\n");
printf("\nOne of the roots of the given equation is:\n\n%lf\n\n\n",x1);
}
OutPut Screen:
output of Newton Raphson Method |
Post a Comment
0 Comments