Stan Math Library  2.10.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 
8  namespace math {
9 
37  template <typename F>
38  void
40  const Eigen::Matrix<double, -1, 1>& x,
41  double& fx,
42  Eigen::Matrix<double, -1, 1>& grad_fx,
43  const double epsilon = 1e-03) {
44  using Eigen::Matrix;
45  using Eigen::Dynamic;
46  Matrix<double, Dynamic, 1> x_temp(x);
47 
48  int d = x.size();
49  grad_fx.resize(d);
50 
51  fx = f(x);
52 
53  for (int i = 0; i < d; ++i) {
54  double delta_f = 0.0;
55 
56  x_temp(i) = x(i) + 3.0 * epsilon;
57  delta_f = f(x_temp);
58 
59  x_temp(i) = x(i) + 2.0 * epsilon;
60  delta_f -= 9.0 * f(x_temp);
61 
62  x_temp(i) = x(i) + epsilon;
63  delta_f += 45.0 * f(x_temp);
64 
65  x_temp(i) = x(i) + -3.0 * epsilon;
66  delta_f -= f(x_temp);
67 
68  x_temp(i) = x(i) + -2.0 * epsilon;
69  delta_f += 9.0 * f(x_temp);
70 
71  x_temp(i) = x(i) + -epsilon;
72  delta_f -= 45.0 * f(x_temp);
73 
74  delta_f /= 60 * epsilon;
75 
76  x_temp(i) = x(i);
77  grad_fx(i) = delta_f;
78  }
79  }
80  }
81 }
82 #endif
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:95
void finite_diff_gradient(const F &f, const Eigen::Matrix< double,-1, 1 > &x, double &fx, Eigen::Matrix< double,-1, 1 > &grad_fx, const 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.