Automatic Differentiation
 
Loading...
Searching...
No Matches
finite_diff_gradient_auto.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUNCTOR_FINITE_DIFF_GRADIENT_AUTO_HPP
2#define STAN_MATH_PRIM_FUNCTOR_FINITE_DIFF_GRADIENT_AUTO_HPP
3
6#include <cmath>
7
8namespace stan {
9namespace math {
10
49template <typename F, typename VectorT,
50 typename ScalarT = return_type_t<VectorT>>
51void finite_diff_gradient_auto(const F& f, const VectorT& x, ScalarT& fx,
52 VectorT& grad_fx) {
53 VectorT 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(value_of_rec(x[i]));
58
59 ScalarT 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
86} // namespace math
87} // namespace stan
88#endif
double value_of_rec(const fvar< T > &v)
Return the value of the specified variable.
void finite_diff_gradient_auto(const F &f, const VectorT &x, ScalarT &fx, VectorT &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.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9