Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 26th, 2012  |  syntax: None  |  size: 1.87 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. /* function prototypes */
  5. double func1(double x);
  6. double func1_d(double x);
  7. double Newton_Raphson(double x0);
  8. int main(int argv, char *argc[])
  9. {
  10.         double x, x_old, f_x_old;
  11.                 printf("\nHomework 6:\n\n      x         f(x)     sign change\n-----------------------------------------\n");
  12.                 for(x=-1.0;x<=5.0;x+=.25) {
  13.                         if((func1(x) < 2.0093) && (func1(x) > -1.9593)) {
  14.                                 printf("%8.2f %12.4f    Y\n", x, func1(x));
  15.                                 printf("     A refined root is %12.6e\n", Newton_Raphson((double)(x+x_old)/2));
  16.                                 continue;
  17.                         }
  18.                         printf("%8.2f %12.4f\n", x, func1(x));
  19.                         x_old = x;
  20.                         f_x_old = func1(x);
  21.                 }
  22.                
  23.                 return (EXIT_SUCCESS);
  24.         //exit(0);/* normal termination */
  25. }
  26. double func1(double x)
  27. {
  28.         return (x*x*x)-(x*x)+(-9.0*x)+8.9;
  29. }
  30. double func1_d(double x)
  31. {
  32.         return (3.0*x*x)+(-2.0*x)-9.0;
  33. }
  34. double Newton_Raphson(double x0)
  35. {/* YOU ARE NOT ALLOWED TO MODIFY THIS FUNCTION */
  36. /* the Newton-Raphson method is used to find a root of f(x) for a given
  37. initial guess x0 */
  38. /* double func1(double x) computes f(x) while double func1_d(double x)
  39. computes f'(x) */
  40.         int debug = 1;
  41.         double tolx, tolf, x1, del_x;
  42.         double f0, f1, f_d0;
  43.         f0 = func1(x0);
  44.         if(debug != 0) printf("     f(%g) = %e \n", x0, f0);
  45. /* define tolerances */
  46.         tolx = 1.e-8 * fabs(x0); /* tolerance for |x1 - x0| */
  47.         tolf = 1.e-6 * fabs(f0); /* tolerance for |f(x1)| */
  48.         do{
  49.                 f_d0 = func1_d(x0);
  50.                 x1 = x0 - f0/f_d0;
  51.                 f1 = func1(x1);
  52.  
  53.                 if(debug != 0) printf("     f(%g) = %e\n", x1, f1);
  54.                 del_x = fabs(x1 - x0);
  55. /* update x0 and f0 for the next iteration */
  56.                 x0 = x1;
  57.                 f0 = f1;
  58.         } while(del_x > tolx && fabs(f1) > tolf);
  59.         return x1;
  60. }