Stan Math Library  2.15.0
reverse mode automatic differentiation
welford_var_estimator.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_WELFORD_VAR_ESTIMATOR_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_WELFORD_VAR_ESTIMATOR_HPP
3 
5 #include <vector>
6 
7 namespace stan {
8  namespace math {
9 
11  public:
12  explicit welford_var_estimator(int n)
13  : m_(Eigen::VectorXd::Zero(n)),
14  m2_(Eigen::VectorXd::Zero(n)) {
15  restart();
16  }
17 
18  void restart() {
19  num_samples_ = 0;
20  m_.setZero();
21  m2_.setZero();
22  }
23 
24  void add_sample(const Eigen::VectorXd& q) {
25  ++num_samples_;
26 
27  Eigen::VectorXd delta(q - m_);
28  m_ += delta / num_samples_;
29  m2_ += delta.cwiseProduct(q - m_);
30  }
31 
32  int num_samples() { return num_samples_; }
33 
34  void sample_mean(Eigen::VectorXd& mean) { mean = m_; }
35 
36  void sample_variance(Eigen::VectorXd& var) {
37  if (num_samples_ > 1)
38  var = m2_ / (num_samples_ - 1.0);
39  }
40 
41  protected:
42  double num_samples_;
43  Eigen::VectorXd m_;
44  Eigen::VectorXd m2_;
45  };
46 
47  }
48 }
49 #endif
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
(Expert) Numerical traits for algorithmic differentiation variables.
void sample_mean(Eigen::VectorXd &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
void add_sample(const Eigen::VectorXd &q)
void sample_variance(Eigen::VectorXd &var)

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