Stan Math Library  2.20.0
reverse mode automatic differentiation
finite_diff_gradient_auto.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_GRADIENT_AUTO_HPP
2 #define STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_GRADIENT_AUTO_HPP
3 
6 #include <cmath>
7 #include <limits>
8 
9 namespace stan {
10 namespace math {
11 
50 template <typename F>
51 void finite_diff_gradient_auto(const F& f, const Eigen::VectorXd& x, double& fx,
52  Eigen::VectorXd& grad_fx) {
53  Eigen::VectorXd x_temp(x);
54  fx = f(x);
55  grad_fx.resize(x.size());
56  for (int i = 0; i < x.size(); ++i) {
57  double h = finite_diff_stepsize(x(i));
58 
59  double delta_f = 0;
60 
61  x_temp(i) = x(i) + 3 * h;
62  delta_f += f(x_temp);
63 
64  x_temp(i) = x(i) + 2 * h;
65  delta_f -= 9 * f(x_temp);
66 
67  x_temp(i) = x(i) + h;
68  delta_f += 45 * f(x_temp);
69 
70  x_temp(i) = x(i) + -3 * h;
71  delta_f -= f(x_temp);
72 
73  x_temp(i) = x(i) + -2 * h;
74  delta_f += 9 * f(x_temp);
75 
76  x_temp(i) = x(i) - h;
77  delta_f -= 45 * f(x_temp);
78 
79  delta_f /= 60 * h;
80 
81  x_temp(i) = x(i);
82  grad_fx(i) = delta_f;
83  }
84 }
85 } // namespace math
86 } // namespace stan
87 #endif
void finite_diff_gradient_auto(const F &f, const Eigen::VectorXd &x, double &fx, Eigen::VectorXd &grad_fx)
Calculate the value and the gradient of the specified function at the specified argument using finite...
double finite_diff_stepsize(double u)
Return the stepsize for finite difference evaluations at the specified scalar.

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