5

我应该在一些蒙特卡罗模拟中计算标准偏差函数。公式是这样的: 在此处输入图像描述

我认为我的结果与应有的结果相去甚远。我的函数使用来自 boost 库的元组,它看起来像这样:

double add_square(double prev_sum, double new_val)
{
  return prev_sum + new_val*new_val;
}

template <typename V>
double vec_add_squares(const V<double>& v)
{
  return std::accumulate(v.begin(), v.end(), 0.0, add_square);
}

    template <class T> 
    boost::tuple<double,double> get_std_dev_and_error(const vector<T>& input, double r, double N)
{
 double M = double(input.size());

 double sum = std::accumulate(input.begin(),input.end(),0.0);
 double Squared_sum = vec_add_squares(input);

 std::cout << "sum " << Squared_sum << endl;

 // Calls Sum
 double term1 = Squared_sum - (sum/M)*sum;

 double SD = (sqrt(term1) * exp(-2.0 * r *N))/(M-1) ;
 double SE = SD/sqrt(M);
 std::cout << "SD = " << SD << endl;
 std::cout << "SE = " << SE << endl;

 return boost::tuple<double,double>(SD, SE) ;
 }
  1. 任何人都可以在这里看到任何错误吗?
  2. 此外,STL 库中有“累积”功能 - 是否存在累积平方(容器成员)?
4

1 回答 1

4

只需使用Boost.Accumulators(因为您已经使用了 boost):

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
#include <ostream>

using namespace boost;
using namespace boost::accumulators;
using namespace std;

int main()
{
    accumulator_set<double, stats<tag::sum , tag::variance, tag::mean > > acc;
    double data[] = {1., 2., 3.};
    acc = for_each(data, acc);
    cout << "sum = " << sum(acc) << endl;
    cout << "variance = " << variance(acc) << endl;
    cout << "sqrt(variance()) = " << sqrt(variance(acc)) << endl;
    cout << "mean = " << mean(acc) << endl;
}

输出是:

sum = 6
variance = 0.666667
sqrt(variance()) = 0.816497
mean = 2
于 2012-11-15T20:16:18.970 回答