I am supposed to compute the standard deviation function in some monte carlo simulations. The formula is this one:
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) ;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With