| Stan Math Library 2.6.3 probability, sampling & optimization

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros
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
4 #include <stan/math/prim/mat/fun/Eigen.hpp>
5 #include <stan/math/prim/mat/fun/mean.hpp>
6 #include <stan/math/prim/scal/err/check_nonzero_size.hpp>
7 #include <boost/math/tools/promotion.hpp>
8 #include <vector>
9
10 namespace stan {
11 namespace math {
12
21 template <typename T>
22 inline
23 typename boost::math::tools::promote_args<T>::type
24 variance(const std::vector<T>& v) {
25 stan::math::check_nonzero_size("variance", "v", v);
26 if (v.size() == 1)
27 return 0.0;
28 T v_mean(mean(v));
29 T sum_sq_diff(0);
30 for (size_t i = 0; i < v.size(); ++i) {
31 T diff = v[i] - v_mean;
32 sum_sq_diff += diff * diff;
33 }
34 return sum_sq_diff / (v.size() - 1);
35 }
36
43 template <typename T, int R, int C>
44 inline
45 typename boost::math::tools::promote_args<T>::type
46 variance(const Eigen::Matrix<T, R, C>& m) {
47 stan::math::check_nonzero_size("variance", "m", m);
48
49 if (m.size() == 1)
50 return 0.0;
51 typename boost::math::tools::promote_args<T>::type
52 mn(mean(m));
53 typename boost::math::tools::promote_args<T>::type
54 sum_sq_diff(0);
55 for (int i = 0; i < m.size(); ++i) {
56 typename boost::math::tools::promote_args<T>::type
57 diff = m(i) - mn;
58 sum_sq_diff += diff * diff;
59 }
60 return sum_sq_diff / (m.size() - 1);
61 }
62
63 }
64 }
65 #endif
stan::math::check_nonzero_size
bool check_nonzero_size(const char *function, const char *name, const T_y &y)
Return true if the specified matrix/vector is of non-zero size.
Definition: check_nonzero_size.hpp:31
stan::math::variance
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:24
mean.hpp
stan::math::mean
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:23
Eigen.hpp
check_nonzero_size.hpp

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