Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include<stdio.

h>
#include<math.h>

/*Function whose root is to be determined*/


double f(double x){
return 3*x+sin(x)-exp(x);
}

/*Derivative of the function whose root is to be determined*/


double df(double x){
return 3-cos(x)-exp(x);
}

int 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;
/*Newton-Raphson Method begins that tabulates the various values at each
iteration*/

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-Condition to prevent division by zero[To be done: Check for infinite
values too]*/
if(fabs(df(x))>=0.000000001&&df(x)!=NAN){
/*New value of x using the NR Expression */
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\nOne of the roots of the given equation is:\n\n%lf\n\n\n",x1);

___________________________________

OUT PUT
____________________________________

Enter the initial guess:


8
Enter the desired accuracy:
0.000001
Enter the max. number of steps:
15
___________________________________________________________________________________
_
x f(x) f'(x) x1 |x-x1| f(x1)
___________________________________________________________________________________
_
1. -2955.968629 -2977.812487 7.007336 0.992664
-1083.022625
2. -1083.022625 -1102.456193 6.024963 0.982372 -395.806835
3. -395.806835 -411.593207 5.063317 0.961646 -143.863272
4. -143.863272 -155.457940 4.137901 0.925416 -51.096924
5. -51.096924 -59.127752 3.273723 0.864178 -16.720055
6. -16.720055 -22.418195 2.527898 0.745825 -4.367558
7. -4.367558 -8.709617 2.026434 0.501464 -0.609700
8. -0.609700 -4.146947 1.879410 0.147024 0.041346
9. 0.041346 -3.245902 1.892148 0.012738 -0.008349
10. -0.008349 -3.317753 1.889632 0.002516 0.001566
11. 0.001566 -3.303470 1.890105 0.000474 -0.000298
12. -0.000298 -3.306156 1.890015 0.000090 0.000057
13. 0.000057 -3.305645 1.890032 0.000017 -0.000011
14. -0.000011 -3.305742 1.890029 0.000003 0.000002
15. 0.000002 -3.305724 1.890030 0.000001 -0.000000
___________________________________________________________________________________
____

One of the roots of the given equation is:

1.890030

Process returned 0 (0x0) execution time : 37.376 s


Press any key to continue.

You might also like