Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic functions for standard deviation in monte carlo C++

I am supposed to compute the standard deviation function in some monte carlo simulations. The formula is this one: enter image description here

I think my results are way off what they should be. My function uses tuples from the boost library and it looks like this:

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. Can anyone see any mistakes here?
  2. also, there is the "accumulate" funciton in the STL library - does there exist an accumulate squared (members of the container)?
like image 637
Mathias Avatar asked Oct 05 '22 23:10

Mathias


1 Answers

Just use Boost.Accumulators (as you already use 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;
}

Output is:

sum = 6
variance = 0.666667
sqrt(variance()) = 0.816497
mean = 2
like image 137
Evgeny Panasyuk Avatar answered Oct 10 '22 01:10

Evgeny Panasyuk