Stan Math Library  2.20.0
reverse mode automatic differentiation
gradient.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_MAT_FUNCTOR_GRADIENT_HPP
2 #define STAN_MATH_FWD_MAT_FUNCTOR_GRADIENT_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 
7 namespace stan {
8 namespace math {
9 
38 template <typename T, typename F>
39 void gradient(const F& f, const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, T& fx,
40  Eigen::Matrix<T, Eigen::Dynamic, 1>& grad_fx) {
41  Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1> x_fvar(x.size());
42  grad_fx.resize(x.size());
43  for (int i = 0; i < x.size(); ++i) {
44  for (int k = 0; k < x.size(); ++k)
45  x_fvar(k) = fvar<T>(x(k), k == i);
46  fvar<T> fx_fvar = f(x_fvar);
47  if (i == 0)
48  fx = fx_fvar.val_;
49  grad_fx(i) = fx_fvar.d_;
50  }
51 }
52 
53 } // namespace math
54 } // namespace stan
55 #endif
T d_
The tangent (derivative) of this variable.
Definition: fvar.hpp:50
T val_
The value of this variable.
Definition: fvar.hpp:45
void gradient(const F &f, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, T &fx, Eigen::Matrix< T, Eigen::Dynamic, 1 > &grad_fx)
Calculate the value and the gradient of the specified function at the specified argument.
Definition: gradient.hpp:39
This template class represents scalars used in forward-mode automatic differentiation, which consist of values and directional derivatives of the specified template type.
Definition: fvar.hpp:41

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