Automatic Differentiation
 
Loading...
Searching...
No Matches
variance.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_VARIANCE_HPP
2#define STAN_MATH_PRIM_FUN_VARIANCE_HPP
3
7#include <vector>
8
9namespace stan {
10namespace math {
11
23template <typename EigMat, require_eigen_t<EigMat>* = nullptr,
24 require_not_vt_var<EigMat>* = nullptr>
25inline value_type_t<EigMat> variance(const EigMat& m) {
26 using value_t = value_type_t<EigMat>;
27 const auto& mat = to_ref(m);
28 check_nonzero_size("variance", "m", mat);
29 if (mat.size() == 1) {
30 return value_t{0.0};
31 }
32 return (mat.array() - mat.mean()).square().sum() / value_t(mat.size() - 1.0);
33}
34
44template <typename StdVec, require_std_vector_t<StdVec>* = nullptr,
45 require_not_vt_var<StdVec>* = nullptr>
46inline value_type_t<StdVec> variance(const StdVec& v) {
47 using eigen_t = Eigen::Matrix<value_type_t<StdVec>, -1, 1>;
48 return variance(Eigen::Map<const eigen_t>(v.data(), v.size()));
49}
50
51} // namespace math
52} // namespace stan
53
54#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
double variance(const T &a)
Return the sample variance of the var_value matrix Raise domain error if size is not greater than zer...
Definition variance.hpp:25
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
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.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...