OPAL (Object Oriented Parallel Accelerator Library)  2.2.0
OPAL
root.cpp
Go to the documentation of this file.
1 /* root.C
2  root finding routines
3 
4  NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)
5 
6  Revision history
7  Date Description Programmer
8  ------------ -------------------------------------------- ------------
9  09-03-2006 Copied from "numerical recipies" Rene Bakker
10 
11  Last Revision:
12  $Id: root.C 29 2007-04-14 17:03:18Z l_bakker $
13 */
14 
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <math.h>
18 
21 
22 /*
23  ======================================================================= */
24 #define MAXIT 100
25 
26 
27 /* findRoot()
28  Originally rtsafe()
29  Using a combination of Newton-Raphson and bisection, find the root of a
30  function bracketed between x1 and x2. The root, returned as the function
31  value rtsafe, will be refined until its accuracy is known within ±xacc.
32  funcd is a user-supplied routine that returns both the function value
33  and the first derivative of the function. */
34 double findRoot
35 (
36  void (*funcd)(double, double *, double *), // function to find root
37  double x1, double x2, // boundaries
38  double xacc) { // accuracy
39  int j;
40  double df, dx, dxold, f, fh, fl;
41  double temp, xh, xl, rts;
42 
43  (*funcd)(x1, &fl, &df);
44  (*funcd)(x2, &fh, &df);
45  if((fl > 0.0 && fh > 0.0) || (fl < 0.0 && fh < 0.0)) {
46  //writeBetError(errModeAll,errFatal,"Root must be bracketed in findRoot()");
47  writeBetError("Root must be bracketed in frindRoot");
48  }
49  if(fl == 0.0) return x1;
50  if(fh == 0.0) return x2;
51  if(fl < 0.0) {
52  xl = x1;
53  xh = x2;
54  } else {
55  xh = x1;
56  xl = x2;
57  }
58  rts = 0.5 * (x1 + x2);
59  dxold = fabs(x2 - x1);
60  dx = dxold;
61  (*funcd)(rts, &f, &df);
62  for(j = 1; j <= MAXIT; j++) {
63  if((((rts - xh)*df - f) * ((rts - xl)*df - f) >= 0.0)
64  || (fabs(2.0 * f) > fabs(dxold * df))) {
65  dxold = dx;
66  dx = 0.5 * (xh - xl);
67  rts = xl + dx;
68  if(xl == rts) return rts;
69  } else {
70  dxold = dx;
71  dx = f / df;
72  temp = rts;
73  rts -= dx;
74  if(temp == rts) return rts;
75  }
76  if(fabs(dx) < xacc) return rts;
77  (*funcd)(rts, &f, &df);
78  if(f < 0.0)
79  xl = rts;
80  else
81  xh = rts;
82  }
83  //writeBetError(errModeAll,errFatal,"Maximum number of iterations (%d) exceeded in findRoot()",MAXIT);
84  writeBetError("Maximum number of iterations exeeded in findRoot");
85 
86  return 0.0;
87 } /* findroot() */
88 
89 #undef MAXIT
90 
double findRoot(void(*funcd)(double, double *, double *), double x1, double x2, double xacc)
Definition: root.cpp:35
void writeBetError(std::string err)
Definition: BetError.cpp:36
PETE_TUTree< FnFabs, typename T::PETE_Expr_t > fabs(const PETE_Expr< T > &l)
Definition: PETE.h:815
#define MAXIT
Definition: root.cpp:24