upsidedown

Newton raphson

Aug 5th, 2011
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<math.h>
  4. #define E 0.0001
  5.  
  6. float f(float x)
  7. {
  8.     return (x*x+x-2);
  9. }
  10.  
  11. float df(float x)
  12. {
  13.     return (2*x+1);
  14. }
  15.  
  16.  
  17.  
  18. main()
  19. {
  20.     float x0,x1,f0,df0;
  21.         int n,i=0;
  22.     printf("enter the value of x and max itrations");
  23.     scanf("%f %d",&x0,&n);
  24.  
  25.     while(i<n)
  26.     {
  27.         f0=f(x0);
  28.         df0=df(x0);
  29.  
  30.         x1= x0- f0/df0;
  31.  
  32.         printf("\n itration %d \t x0= %f",(i+1),x0);
  33.  
  34.         if(fabs((x1-x0)/x1) < E)
  35.         {
  36.             printf("\n the root is %f in %d iterations",x0,(i+1));
  37.             exit(0);
  38.         }
  39.  
  40.         x0=x1;
  41.         i++;
  42.     }
  43.  
  44.     printf("the roots do not converge in %d itrations",n);
  45.     return 0;
  46. }
  47.  
  48.  
  49. OUTPUT:
  50. enter the value of x and max itrations-10
  51. 50
  52.  
  53.  itration 1      x0= -10.000000
  54.  itration 2      x0= -5.368421
  55.  itration 3      x0= -3.165292
  56.  itration 4      x0= -2.254739
  57.  itration 5      x0= -2.018490
  58.  itration 6      x0= -2.000113
  59.  the root is -2.000113 in 6 iterations
Advertisement
Add Comment
Please, Sign In to add comment