//
// source code: newton_cos.cc 
// purpose:     Newton iteration - example
// author:      T. Hebbeker   
// version:     1.0, 2006-10-30
//
//     note: program finds ONE solution - there might be many...
//  

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;

const double PI=3.1415926536;


double g (double x)
{
  return 0.5 - cos(x);
}

double g_derivative (double x)
{
  return sin(x);
}


int main()
{
  cout << endl 
       << " program   === newton_cos ===   version 1.0 " 
       << endl
       << endl;

  double        x_old = 1.0;             // start value

  const double  epsilon = 1E-8;
  const double  delta = 1E-2;
  const int     n = 10;                  // number iterations
  double        x_veryold = x_old+delta;
  double        x_new;
  double        g_v;                     // value of function g   
  double        g_d;                     // derivative of function g   

  for (int i=1; i<n; i++)
  {
    g_v = g(x_old);
    g_d = g_derivative(x_old);

    if(fabs(g_d) > epsilon) 
    {
      x_new = x_old - g_v/g_d;
    }
    else    // apply last step     old -> new    once again 
            //     to avoid divide check 
    {
      cout << " warning: vanishing derivative " << endl;
      x_new = x_old + (x_old - x_veryold);
    }

    cout << i << " " << setprecision(12) << x_new << endl;

    x_veryold = x_old; 
    x_old = x_new;
  }

  return 0;
}





