icedb  version 0.5.1
Snow particle scattering database API
zeros.hpp
Go to the documentation of this file.
1 #pragma once
2 #include "defs.h"
3 
4 #include <complex>
5 #include <functional>
6 
7 #include "error.hpp"
8 
9 namespace icedb {
10 
11  namespace zeros {
13  double findzero(double a, double b, const std::function<double(double) > & evaltarget);
14 
15  // f is an arbitrary class with operator(). So, a functional / lambda function does work.
16  template<class T, class U>
17  U secantMethod(const T &f,
18  U guess_a, U guess_b,
19  double eps = 0.000001, size_t maxIter = 50)
20  {
21  // Secant method is defined by recurrance
22  // xn = x_(n-1) - f(x_(n-1)) * (x_(n-1) - x_(n-2)) / (f(x_(n-1)) - f(x_(n-2)))
23  using namespace std;
24  U zero;
25  U xn = guess_a, xn1 = guess_b, xn2;
26  U fxn1, fxn2;
27  size_t i=0;
28  do {
29  xn2 = xn1;
30  xn1 = xn;
31 
32  fxn1 = f(xn1);
33  fxn2 = f(xn2);
34 
35  xn = xn1 - fxn1 * (xn1 - xn2) / (fxn1 - fxn2);
36  } while ( (abs(xn-xn1) > eps) && (i++ < maxIter));
37 
39  .add<size_t>("maxIter", maxIter)
40  .add<double>("eps", eps)
41  .template add<U>("guess_a", guess_a)
42  .template add<U>("guess_b", guess_b)
43  .template add<U>("xn",xn)
44  .template add<U>("xn1",xn1)
45  .template add<U>("xn2",xn2)
46  .template add<U>("fxn1",fxn1)
47  .template add<U>("fxn2",fxn2);
48  zero = xn;
49  return zero;
50  }
51 
52  }
53 
54 }
55 
STL namespace.
U secantMethod(const T &f, U guess_a, U guess_b, double eps=0.000001, size_t maxIter=50)
Definition: zeros.hpp:17
#define ICEDB_throw(x)
Definition: error.hpp:88
double findzero(double a, double b, const std::function< double(double) > &f)
Zero-finding implementation - Brent&#39;s method.
Definition: zeros.cpp:7