there is my robbinsmonro.hpp:
#include <utility>
#ifndef ROBBINS_HPP
#define ROBBINS_HPP
template <class Func, class DetermSeq, class RandomV, class RNG>
std::pair<double,double> robbins_monro( const Func & h, double x_init,
double alpha, const DetermSeq & epsilon,RandomV & U, RNG & G,
long unsigned N)
{
for(unsigned i=0; i<N; i++)
{
x_init = x_init - epsilon(i+1)*(h(x_init) - alpha + U(G));
}
return std::make_pair(x_init, h(x_init));
}
#endif
And there is my test1.cpp:
#include "robbinsmonro.hpp"
#include <ctime>
#include <random>
#include <cmath>
#include <iostream>
int main() {
auto f = [](double x) {return 1./(1.+exp(-x));};
std::mt19937 G(time(nullptr));
double alpha = 2./3.;
auto epsilon = [](long unsigned N) { return 1./(N+1.);};
std::uniform_real_distribution<double> U(-0.1,0.1);
long unsigned N = 1000000;
double variance=0.;
double esperance=0.;
int K = 100;
std::pair<double,double> y = std::make_pair(0,0);
for(int i=0; i<K; i++) {
y = robbins_monro(f,0.,alpha,epsilon,U,G,N);
variance += std::get<0>(y)*std::get<0>(y);
esperance += std::get<0>(y);
}
variance /= double(K);
esperance /= double(K);
std::cout << "La variance empirique pour N=1000000 est de " << variance - esperance*esperance << std::endl;
return 0;
}
And there is another code of the test1.cpp (not from me):
#include <random>
#include <iostream>
#include "robbinsmonro.hpp"
int main() {
auto h=[](double x) { return 1./(1.+exp(-x)); };
double alpha=2./3.;
auto epsilon=[](long unsigned n) { return 1./(n+1.);};
std::uniform_real_distribution<double> U(-0.1,0.1);
std::mt19937 G(time(nullptr));
std::pair<double,double> p;
long unsigned N;
double m;
double v;
int K=100;
N=100000;
m=0.;
v=0.;
for (int i = 0; i < K; i++)
{
p=robbins_monro(h,0.,alpha,epsilon,U,G,N);
m += p.first;
v += p.first*p.first;
}
return 0;
}
When I calculate the empirical variance, my code takes much longer to run to give a factor 2 error. Yet my code is exactly the same, isn't it?
As I said in my comment, the value of N is different in each program, which seems to have solved the issue.
If you are using c++14 or newer this can be easily avoided by writing long numbers using the digit separator - you can optionally place a single quote anywhere in the number to aid readability.
eg
int N=1'000'000
and
int N=100'000
are very clearly different.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.