Stan Math Library  2.9.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 
9  namespace math {
10 
40  template <typename T, typename F>
41  void
42  gradient(const F& f,
43  const Eigen::Matrix<T, Eigen::Dynamic, 1>& x,
44  T& fx,
45  Eigen::Matrix<T, Eigen::Dynamic, 1>& grad_fx) {
46  Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1> x_fvar(x.size());
47  grad_fx.resize(x.size());
48  for (int i = 0; i < x.size(); ++i) {
49  for (int k = 0; k < x.size(); ++k)
50  x_fvar(k) = fvar<T>(x(k), k == i);
51  fvar<T> fx_fvar = f(x_fvar);
52  if (i == 0) fx = fx_fvar.val_;
53  grad_fx(i) = fx_fvar.d_;
54  }
55  }
56 
57  } // namespace math
58 } // namespace stan
59 #endif
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:42

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