/* Adaptado de Numerical Recipes in C */

#include <stdio.h>
#include <math.h>
#include "protos.h"

#define JMAX 20 /* Set to maximum number of iterations. */

float rtnewt(float x1, float x2, float xacc)
/* Using the Newton-Raphson method, find the root of a function known to lie in the interval
[x1, x2]. The root rtnewt will be refined until its accuracy is known within +/- xacc. funcd
is a user-supplied routine that returns both the function value and the first derivative of the
function at the point x.
*/
{
  int j;
  float df,dx,f,rtn;
  rtn=0.5*(x1+x2); /* Initial guess. */
  for (j=1;j<=JMAX;j++) {
    funcd(rtn,&f,&df);
    dx=f/df;
    rtn -= dx;
    if ((x1-rtn)*(rtn-x2) < 0.0)
      printf("Candidato a raiz saiu fora do intervalo de busca\n");
    
    if (fabs(dx) < xacc) return rtn; /* Convergence. */
  }
  printf("Numero maximo de iteracoes excedido em rtnewt\n ");
  return 0.0; /* Never get here. */
}
