/*************************    Program 2.8    ****************************/
/*                                                                      */
/************************************************************************/
/* Please Note:                                                         */
/*                                                                      */
/* (1) This computer program is written by Tao Pang in conjunction with */
/*     his book, "An Introduction to Computational Physics," published  */
/*     by Cambridge University Press in 1997.                           */
/*                                                                      */
/* (2) No warranties, express or implied, are made for this program.    */
/*                                                                      */
/************************************************************************/

#include <stdio.h>
#include <math.h>
#define f(x) (exp(x)*log(x)-x*x)

main()
/* Main program to use the Secant Method to find the root of
   f(x)=exp(x)*ln(x)-x*x=0.  Copyright (c) Tao Pang 1997. */
{
int istep;
double dl=1e-6;
double a,b,xi,xf,di,df;
void secant ();

a = 1; b = 2;
di = (b-a)/10;
xi = (a+b)/2;
secant (dl,xi,di,&xf,&df,&istep);
printf("%4d %16.8lf %16.8lf\n", istep,xf,df);
}

void secant (dl,xi,di,xf,df,istep)
/* Subroutine for the root of f(x)=0 with the secant method.
   Copyright (c) Tao Pang 1997. */
int *istep;
double dl,xi,di;
double *xf,*df;
{
double x0,x1,x2,d;

x0 = xi;
x1 = xi+di;
*df = di;
*istep = 0;
while (fabs(*df) > dl)
  {
  d = f(x1)-f(x0);
  x2 = x1-f(x1)*(x1-x0)/d;
  x0 = x1;
  x1 = x2;
  *df = x1-x0;
  *istep = *istep+1;
  }
  *xf = x0;
}
