Stan Math Library  2.15.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
43  const Eigen::Matrix<double, -1, 1>& x,
44  double& fx,
45  Eigen::Matrix<double, -1, -1>& hess,
46  std::vector<Eigen::Matrix<double, -1, -1> >&
47  grad_hess_fx,
48  double epsilon = 1e-04) {
49  using Eigen::Matrix;
50  using Eigen::Dynamic;
51 
52  int d = x.size();
53  double dummy_fx_eval;
54 
55  Matrix<double, Dynamic, 1> x_temp(x);
56  Matrix<double, Dynamic, 1> grad_auto(d);
57  Matrix<double, Dynamic, Dynamic> hess_auto(d, d);
58  Matrix<double, Dynamic, Dynamic> hess_diff(d, d);
59 
60  hessian(f, x, fx, grad_auto, hess);
61  for (int i = 0; i < d; ++i) {
62  hess_diff.setZero();
63 
64  x_temp(i) = x(i) + 2.0 * epsilon;
65  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
66  hess_diff = -hess_auto;
67 
68  x_temp(i) = x(i) + -2.0 * epsilon;
69  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
70  hess_diff += hess_auto;
71 
72  x_temp(i) = x(i) + epsilon;
73  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
74  hess_diff += 8.0 * hess_auto;
75 
76  x_temp(i) = x(i) + -epsilon;
77  hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
78  hess_diff -= 8.0 * hess_auto;
79 
80  x_temp(i) = x(i);
81  hess_diff /= 12.0 * epsilon;
82 
83  grad_hess_fx.push_back(hess_diff);
84  }
85  fx = f(x);
86  }
87 
88  }
89 }
90 #endif
void hessian(const F &f, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &x, double &fx, Eigen::Matrix< double, Eigen::Dynamic, 1 > &grad, Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > &H)
Calculate the value, the gradient, and the Hessian, of the specified function at the specified argume...
Definition: hessian.hpp:44
void finite_diff_grad_hessian(const F &f, const Eigen::Matrix< double, -1, 1 > &x, double &fx, Eigen::Matrix< double, -1, -1 > &hess, std::vector< Eigen::Matrix< double, -1, -1 > > &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:94

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