提问者:小点点

我不明白为什么我的代码不能工作并且运行时间更长


这是我的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

这是我的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;
}

还有另一段test1.cpp代码(不是来自我):

#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;
}

当我计算经验方差时,我的代码运行时间要长得多才能给出因子2的错误。 但我的代码是完全一样的,不是吗?


共1个答案

匿名用户

正如我在评论中所说的,N的值在每个程序中都是不同的,这似乎解决了这个问题。

如果您使用的是C++14或更高版本,可以通过使用数字分隔符编写长数字来轻松避免这种情况-您可以在数字中任意位置放置一个单引号以提高可读性。

例如。

int N=1'000'000

int N=100'000

非常明显的不同。