1 #ifndef STAN_MATH_REV_MAT_FUN_SD_HPP
2 #define STAN_MATH_REV_MAT_FUN_SD_HPP
8 #include <boost/math/tools/promotion.hpp>
20 var calc_sd(
size_t size,
25 .
alloc(size *
sizeof(vari*)));
26 for (
size_t i = 0; i <
size; ++i)
27 varis[i] = dtrs[i].vi_;
29 for (
size_t i = 0; i <
size; ++i)
30 sum += dtrs[i].vi_->val_;
31 double mean = sum / size;
32 double sum_of_squares = 0;
33 for (
size_t i = 0; i <
size; ++i) {
34 double diff = dtrs[i].vi_->val_ -
mean;
35 sum_of_squares += diff * diff;
37 double variance = sum_of_squares / (size - 1);
38 double sd =
sqrt(variance);
41 .
alloc(size *
sizeof(
double)));
42 if (sum_of_squares < 1
e-20) {
43 double grad_limit = 1 /
std::sqrt(static_cast<double>(size));
44 for (
size_t i = 0; i <
size; ++i)
45 partials[i] = grad_limit;
47 double multiplier = 1 / (sd * (size - 1));
48 for (
size_t i = 0; i <
size; ++i)
49 partials[i] = multiplier * (dtrs[i].vi_->val_ -
mean);
51 return var(
new stored_gradient_vari(sd, size,
64 inline var sd(
const std::vector<var>& v) {
66 if (v.size() == 1)
return 0;
67 return calc_sd(v.size(), &v[0]);
80 template <
int R,
int C>
81 var sd(
const Eigen::Matrix<var, R, C>& m) {
83 if (m.size() == 1)
return 0;
84 return calc_sd(m.size(), &m(0));
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
fvar< T > sqrt(const fvar< T > &x)
static stack_alloc memalloc_
Independent (input) and dependent (output) variables for gradients.
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.
boost::math::tools::promote_args< T >::type sd(const std::vector< T > &v)
Returns the unbiased sample standard deviation of the coefficients in the specified column vector...
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...
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...
double e()
Return the base of the natural logarithm.
int size(const std::vector< T > &x)
Return the size 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...