1 #ifndef STAN__AGRAD__REV__MATRIX__VARIANCE_HPP
2 #define STAN__AGRAD__REV__MATRIX__VARIANCE_HPP
6 #include <boost/math/tools/promotion.hpp>
23 var calc_sd(
size_t size,
27 for (
size_t i = 0; i <
size; ++i)
28 varis[i] = dtrs[i].vi_;
30 for (
size_t i = 0; i <
size; ++i)
31 sum += dtrs[i].vi_->val_;
32 double mean = sum / size;
33 double sum_of_squares = 0;
34 for (
size_t i = 0; i <
size; ++i) {
35 double diff = dtrs[i].vi_->val_ -
mean;
36 sum_of_squares += diff * diff;
38 double variance = sum_of_squares / (size - 1);
39 double sd =
sqrt(variance);
40 double* partials = (
double*)
memalloc_.
alloc(size *
sizeof(
double));
41 if (sum_of_squares < 1
e-20) {
42 double grad_limit = 1 /
std::sqrt((
double)size);
43 for (
size_t i = 0; i <
size; ++i)
44 partials[i] = grad_limit;
46 double multiplier = 1 / (sd * (size - 1));
47 for (
size_t i = 0; i <
size; ++i)
48 partials[i] = multiplier * (dtrs[i].vi_->val_ -
mean);
50 return var(
new stored_gradient_vari(sd, size,
63 var sd(
const std::vector<var>& v) {
65 if (v.size() == 1)
return 0;
66 return calc_sd(v.size(), &v[0]);
79 template <
int R,
int C>
80 var sd(
const Eigen::Matrix<var,R,C>& m) {
82 if (m.size() == 1)
return 0;
83 return calc_sd(m.size(), &m(0));
memory::stack_alloc memalloc_
fvar< T > sum(const Eigen::Matrix< fvar< T >, R, C > &m)
fvar< T > sqrt(const fvar< T > &x)
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...
var sd(const std::vector< var > &v)
Return the sample standard deviation of the specified standard vector.
void * alloc(size_t len)
Return a newly allocated block of memory of the appropriate size managed by the stack allocator...
Independent (input) and dependent (output) variables for gradients.
double e()
Return the base of the natural logarithm.
int size(const std::vector< T > &x)
var variance(const std::vector< var > &v)
Return the sample variance of the specified standard vector.
bool check_nonzero_size(const char *function, const T_y &y, const char *name, T_result *result)
Return true if the specified matrix/vector is of non-zero size.