namereq

ニュートン法

Jun 27th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.84 KB | None | 0 0
  1. /*
  2. newton.c: ニュートン法
  3. */
  4. #include <stdio.h> // printf, fprintf, fgets, sscanf
  5. #include <math.h> // fabs
  6.  
  7. double newton(double a,double eps)
  8. {
  9.     int n = 0;
  10.     double x0, err, x;
  11.     x = (a + 1.0) / 2.0;
  12.     printf("# n, x, err\n");
  13.     printf("%4d, %.15e\n", n, x);
  14.     do {
  15.         n++;
  16.         x0 = x;
  17.         x = 1.0 / 2 * (x0 + a / x0);
  18.         err = fabs(x - x0);
  19.         printf("%4d, %.15e, %.15e\n", n, x, err);
  20.     } while (err >= eps);
  21.     return x;
  22. }
  23.  
  24. int main(void)
  25. {
  26.     int n = 0;
  27.     double a = 0, x, x0, err, eps = 1.0e-10;
  28.     char s[128];
  29.    
  30.     fprintf(stderr, " a = "); fgets(s, 128, stdin); sscanf(s, "%lf", &a);
  31.     while (a <= 0.0) {
  32.         fprintf(stderr, "'a' には正の数を入れてください。\n");
  33.         fprintf(stderr, " a = "); fgets(s, 128, stdin); sscanf(s, "%lf", &a);
  34.     }
  35.  
  36.     x = newton(a, eps);
  37.     printf("\n# sqrt(%e) = %.15e\n", a, x);
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment