Stan Math Library  2.20.0
reverse mode automatic differentiation
finite_diff_grad_hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_FINITE_DIFF_GRAD_HESSIAN_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_FINITE_DIFF_GRAD_HESSIAN_HPP
3 
5 #include <stan/math/rev/core.hpp>
7 #include <vector>
8 
9 namespace stan {
10 namespace math {
11 
40 template <typename F>
41 void finite_diff_grad_hessian(const F& f, const Eigen::VectorXd& x, double& fx,
42  Eigen::MatrixXd& hess,
43  std::vector<Eigen::MatrixXd>& grad_hess_fx,
44  double epsilon = 1e-04) {
45  int d = x.size();
46  grad_hess_fx.clear();
47 
48  Eigen::VectorXd x_temp(x);
49  Eigen::VectorXd grad_auto(d);
50  Eigen::MatrixXd hess_auto(d, d);
51  Eigen::MatrixXd hess_diff(d, d);
52 
53  hessian(f, x, fx, grad_auto, hess);
54  for (int i = 0; i < d; ++i) {
55  double dummy_fx_eval;
56  hess_diff.setZero();
57 
58  x_temp(i) = x(i) + 2.0 * epsilon;
59  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
60  hess_diff = -hess_auto;
61 
62  x_temp(i) = x(i) + -2.0 * epsilon;
63  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
64  hess_diff += hess_auto;
65 
66  x_temp(i) = x(i) + epsilon;
67  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
68  hess_diff += 8.0 * hess_auto;
69 
70  x_temp(i) = x(i) + -epsilon;
71  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
72  hess_diff -= 8.0 * hess_auto;
73 
74  x_temp(i) = x(i);
75  hess_diff /= 12.0 * epsilon;
76 
77  grad_hess_fx.push_back(hess_diff);
78  }
79  fx = f(x);
80 }
81 
82 } // namespace math
83 } // namespace stan
84 #endif
void hessian(const F &f, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, T &fx, Eigen::Matrix< T, Eigen::Dynamic, 1 > &grad, Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &H)
Calculate the value, the gradient, and the Hessian, of the specified function at the specified argume...
Definition: hessian.hpp:41
void finite_diff_grad_hessian(const F &f, const Eigen::VectorXd &x, double &fx, Eigen::MatrixXd &hess, std::vector< Eigen::MatrixXd > &grad_hess_fx, double epsilon=1e-04)
Calculate the value and the gradient of the hessian of the specified function at the specified argume...
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:87

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