Stan Math Library  2.20.0
reverse mode automatic differentiation
variance.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP
3 
7 #include <boost/math/tools/promotion.hpp>
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
21 template <typename T>
22 inline typename boost::math::tools::promote_args<T>::type variance(
23  const std::vector<T>& v) {
24  check_nonzero_size("variance", "v", v);
25  if (v.size() == 1)
26  return 0.0;
27  T v_mean(mean(v));
28  T sum_sq_diff(0);
29  for (size_t i = 0; i < v.size(); ++i) {
30  T diff = v[i] - v_mean;
31  sum_sq_diff += diff * diff;
32  }
33  return sum_sq_diff / (v.size() - 1);
34 }
35 
42 template <typename T, int R, int C>
43 inline typename boost::math::tools::promote_args<T>::type variance(
44  const Eigen::Matrix<T, R, C>& m) {
45  check_nonzero_size("variance", "m", m);
46 
47  if (m.size() == 1)
48  return 0.0;
49  typename boost::math::tools::promote_args<T>::type mn(mean(m));
50  typename boost::math::tools::promote_args<T>::type sum_sq_diff(0);
51  for (int i = 0; i < m.size(); ++i) {
52  typename boost::math::tools::promote_args<T>::type diff = m(i) - mn;
53  sum_sq_diff += diff * diff;
54  }
55  return sum_sq_diff / (m.size() - 1);
56 }
57 
58 } // namespace math
59 } // namespace stan
60 #endif
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
boost::math::tools::promote_args< T >::type variance(const std::vector< T > &v)
Returns the sample variance (divide by length - 1) of the coefficients in the specified standard vect...
Definition: variance.hpp:22
boost::math::tools::promote_args< T >::type mean(const std::vector< T > &v)
Returns the sample mean (i.e., average) of the coefficients in the specified standard vector...
Definition: mean.hpp:21

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