| Stan Math Library 2.11.0 reverse mode automatic differentiation

- Main Page
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

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
4 #include <stan/math/prim/mat/fun/Eigen.hpp>
5 #include <stan/math/rev/core.hpp>
6 #include <stan/math/mix/mat/functor/hessian.hpp>
7 #include <vector>
8
9 namespace stan {
10
11 namespace math {
12
41 template <typename F>
42 void
43 finite_diff_grad_hessian(const F& f,
44 const Eigen::Matrix<double, -1, 1>& x,
45 double& fx,
46 Eigen::Matrix<double, -1, -1>& hess,
47 std::vector<Eigen::Matrix<double, -1, -1> >&
48 grad_hess_fx,
49 const double epsilon = 1e-04) {
50 using Eigen::Matrix;
51 using Eigen::Dynamic;
52
53 int d = x.size();
54 double dummy_fx_eval;
55
56 Matrix<double, Dynamic, 1> x_temp(x);
57 Matrix<double, Dynamic, 1> grad_auto(d);
58 Matrix<double, Dynamic, Dynamic> hess_auto(d, d);
59 Matrix<double, Dynamic, Dynamic> hess_diff(d, d);
60
61 hessian(f, x, fx, grad_auto, hess);
62 for (int i = 0; i < d; ++i) {
63 hess_diff.setZero();
64
65 x_temp(i) = x(i) + 2.0 * epsilon;
66 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
67 hess_diff = -hess_auto;
68
69 x_temp(i) = x(i) + -2.0 * epsilon;
70 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
71 hess_diff += hess_auto;
72
73 x_temp(i) = x(i) + epsilon;
74 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
75 hess_diff += 8.0 * hess_auto;
76
77 x_temp(i) = x(i) + -epsilon;
78 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
79 hess_diff -= 8.0 * hess_auto;
80
81 x_temp(i) = x(i);
82 hess_diff /= 12.0 * epsilon;
83
84 grad_hess_fx.push_back(hess_diff);
85 }
86 fx = f(x);
87 }
88
89 }
90 }
91 #endif
stan::math::hessian
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:45
core.hpp
stan
Definition: log_sum_exp.hpp:8
stan::math::finite_diff_grad_hessian
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, const double epsilon=1e-04)
Calculate the value and the gradient of the hessian of the specified function at the specified argume...
Definition: finite_diff_grad_hessian.hpp:43
hessian.hpp
Eigen.hpp
stan::math::e
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:95

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