[ create a new paste ] login | about

Link: http://codepad.org/eKC9f5qt    [ raw code | output | fork ]

C++, pasted on May 10:
#include <stdio.h>
#include <math.h>
double f(double x) { return exp(-x)-x*x; }
double df(double x) { return -exp(-x)-2*x; }
int main()
{
  double x, y, dy, dx;
  int i;

  x = 1.0;
  printf(" i              x                      f(x)                     f'(x)\n");
  printf("--: ------------------------ ------------------------ ------------------------\n");
  for (i = 0;; i++) {
    y = f(x);
    dy = df(x);
    printf("%2d: %24.17g %24.17g %24.17g\n", i, x, y, dy);
    if (i >= 10 || y == 0) break;
    if (dy == 0) {
      printf("Keisan funou.");
      abort();
    }
    dx = -y / dy;
    if (fabs(dx) < fabs(x) * 1e-17) {
      printf("%2d: %24.17g\n", i + 1, x + dx);
      break;
    }
    x += dx;
  }
  return 0;
}


Output:
1
2
3
4
5
6
7
8
9
 i              x                      f(x)                     f'(x)
--: ------------------------ ------------------------ ------------------------
 0:                        1     -0.63212055882855767      -2.3678794411714423
 1:      0.73304360524544543    -0.056908448004025426       -1.946531689678106
 2:      0.70380778632413299  -0.00064739153874653239      -1.9023135811999958
 3:      0.70346746833179752  -8.7166030608845169e-08       -1.901801328498713
 4:      0.70346742249839245  -1.4891516839088403e-15      -1.9018012595133151
 5:      0.70346742249839167  -7.1557343384043293e-18       -1.901801259513314
 6:      0.70346742249839167


Create a new paste based on this one


Comments: