Stan Math Library  2.15.0
reverse mode automatic differentiation
finite_diff_gradient.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_GRADIENT_HPP
2 #define STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_GRADIENT_HPP
3 
5 
6 namespace stan {
7  namespace math {
8 
36  template <typename F>
37  void
39  const Eigen::Matrix<double, -1, 1>& x,
40  double& fx,
41  Eigen::Matrix<double, -1, 1>& grad_fx,
42  double epsilon = 1e-03) {
43  using Eigen::Matrix;
44  using Eigen::Dynamic;
45  Matrix<double, Dynamic, 1> x_temp(x);
46 
47  int d = x.size();
48  grad_fx.resize(d);
49 
50  fx = f(x);
51 
52  for (int i = 0; i < d; ++i) {
53  double delta_f = 0.0;
54 
55  x_temp(i) = x(i) + 3.0 * epsilon;
56  delta_f = f(x_temp);
57 
58  x_temp(i) = x(i) + 2.0 * epsilon;
59  delta_f -= 9.0 * f(x_temp);
60 
61  x_temp(i) = x(i) + epsilon;
62  delta_f += 45.0 * f(x_temp);
63 
64  x_temp(i) = x(i) + -3.0 * epsilon;
65  delta_f -= f(x_temp);
66 
67  x_temp(i) = x(i) + -2.0 * epsilon;
68  delta_f += 9.0 * f(x_temp);
69 
70  x_temp(i) = x(i) + -epsilon;
71  delta_f -= 45.0 * f(x_temp);
72 
73  delta_f /= 60 * epsilon;
74 
75  x_temp(i) = x(i);
76  grad_fx(i) = delta_f;
77  }
78  }
79  }
80 }
81 #endif
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:94
void finite_diff_gradient(const F &f, const Eigen::Matrix< double, -1, 1 > &x, double &fx, Eigen::Matrix< double, -1, 1 > &grad_fx, double epsilon=1e-03)
Calculate the value and the gradient of the specified function at the specified argument using finite...

     [ Stan Home Page ] © 2011–2016, Stan Development Team.