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

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