variance.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP
#define STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP
#include <stan/math/prim/arr/err/check_nonzero_size.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/mean.hpp>
#include <boost/math/tools/promotion.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T>
inline
typename boost::math::tools::promote_args<T>::type
variance(const std::vector<T>& v) {
check_nonzero_size("variance", "v", v);
if (v.size() == 1)
return 0.0;
T v_mean(mean(v));
T sum_sq_diff(0);
for (size_t i = 0; i < v.size(); ++i) {
T diff = v[i] - v_mean;
sum_sq_diff += diff * diff;
}
return sum_sq_diff / (v.size() - 1);
}
template <typename T, int R, int C>
inline
typename boost::math::tools::promote_args<T>::type
variance(const Eigen::Matrix<T, R, C>& m) {
check_nonzero_size("variance", "m", m);
if (m.size() == 1)
return 0.0;
typename boost::math::tools::promote_args<T>::type
mn(mean(m));
typename boost::math::tools::promote_args<T>::type
sum_sq_diff(0);
for (int i = 0; i < m.size(); ++i) {
typename boost::math::tools::promote_args<T>::type
diff = m(i) - mn;
sum_sq_diff += diff * diff;
}
return sum_sq_diff / (m.size() - 1);
}
}
}
#endif
stan::math::check_nonzero_size
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.
Definition: check_nonzero_size.hpp:27
stan
Definition: log_sum_exp.hpp:8
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–2016, Stan Development Team.