Stan Math Library  2.20.0
reverse mode automatic differentiation
finite_diff_hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_HESSIAN_HPP
2 #define STAN_MATH_PRIM_MAT_FUNCTOR_FINITE_DIFF_HESSIAN_HPP
3 
8 
9 namespace stan {
10 namespace math {
11 
35 template <typename F>
36 void finite_diff_hessian(const F& f, const Eigen::VectorXd& x, double& fx,
37  Eigen::VectorXd& grad_fx, Eigen::MatrixXd& hess_fx,
38  double epsilon = 1e-03) {
39  int d = x.size();
40  Eigen::VectorXd x_temp(x);
41  hess_fx.resize(d, d);
42  finite_diff_gradient(f, x, fx, grad_fx);
43  for (int i = 0; i < d; ++i) {
44  for (int j = i; j < d; ++j) {
45  double f_diff = 0;
46  x_temp(i) += 2 * epsilon;
47  if (i != j) {
48  f_diff = -finite_diff_hessian_helper(f, x_temp, j);
49  x_temp(i) = x(i) + -2 * epsilon;
50  f_diff += finite_diff_hessian_helper(f, x_temp, j);
51  x_temp(i) = x(i) + epsilon;
52  f_diff += 8 * finite_diff_hessian_helper(f, x_temp, j);
53  x_temp(i) = x(i) + -epsilon;
54  f_diff -= 8 * finite_diff_hessian_helper(f, x_temp, j);
55  f_diff /= 12 * epsilon * 12 * epsilon;
56  } else {
57  f_diff = -f(x_temp);
58  f_diff -= 30 * fx;
59  x_temp(i) = x(i) + -2 * epsilon;
60  f_diff -= f(x_temp);
61  x_temp(i) = x(i) + epsilon;
62  f_diff += 16 * f(x_temp);
63  x_temp(i) = x(i) - epsilon;
64  f_diff += 16 * f(x_temp);
65  f_diff /= 12 * epsilon * epsilon;
66  }
67  x_temp(i) = x(i);
68  hess_fx(j, i) = f_diff;
69  hess_fx(i, j) = hess_fx(j, i);
70  }
71  }
72 }
73 } // namespace math
74 } // namespace stan
75 #endif
void finite_diff_hessian(const F &f, const Eigen::VectorXd &x, double &fx, Eigen::VectorXd &grad_fx, Eigen::MatrixXd &hess_fx, double epsilon=1e-03)
Calculate the value and the Hessian of the specified function at the specified argument using second-...
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 finite_diff_hessian_helper(const F &f, const Eigen::VectorXd &x, int i, double epsilon=1e-03)
Return the subcalculation required by finite_diff_hessian and finite_diff_hessian_auto.
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:87

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