简体   繁体   English

正确生成随机指数值C ++

[英]Generate random exponential value correctly c++

I want to generate random number belonging to an exponential distribution. 我想生成属于指数分布的随机数。 I wrote this 我写了这个

    int size = atoi(argv[2]);
    double *values = (double*)malloc(sizeof(double)*size);

    double gamma = atof(argv[1]);
    if(gamma<=0.0){
        cout<<"Insert gamma"<<endl;
        return 0;
    }


    for(int i=0; i<size; i++){
        values[i]=0;

    }

    srand ( time(NULL) );
    for(int i=0; i<size; i++){
        x = ((double) rand() / (RAND_MAX));
        //cout << random <<endl;
        value=(log(1.0-x)/(-gamma));
        //count each value
        values[value]=values[value]+1.0;
    }

But they do not cover all the vector's size. 但是它们并不能覆盖所有向量的大小。 More or less they cover 10% of the vector, the other fields are all 0 and due to the fact that after I need to do a linear interpolation I want to reduce those 'empty space' in order to have at least one value for each cell of the array, How can I do it? 它们或多或少地覆盖了矢量的10%,其他字段全为0,并且由于以下事实:在我需要进行线性插值后,我想减少那些“空白空间”,以便每个字段至少有一个值数组的单元格,我该怎么办? for example I have a vector of 100000 only the first 60 fields are filled with values so cells from 60 to 999999 are all 0 and when I do linear regression they impact negatively on formula. 例如,我有一个100000的向量,只有前60个字段填充了值,因此60到999999的单元格都为0,当我进行线性回归时,它们对公式产生负面影响。

Ok, I see the bug 好的,我看到了错误

You'er generating size number of events. 而你却被发电size数量的事件。 You really need more events to fill the histogram 您确实需要更多事件来填充直方图

PS PS

Probability for fill bin #n (n is in the range [0...size)) is given by expression 填充仓#n(n在[0 ... size]范围内)的概率由表达式给出

prob = exp(-gamma*n) - exp(-gamma*(n+1))

which for gamma equal to 0.01 and, say, n about 1000 will give you probability of about 4*10^-7 . 对于gamma等于0.01,例如n约为1000,则您的概率约为4*10^-7 So to get even one event in this bin you'll need to sample about 2.5million times 因此,要在该容器中获得一个事件,就需要采样约250万次

PPS PPS

and using library exponential sampling while it is good in general, won't buy you anything because as far as I know you sampling is ok 并在一般情况下使用库指数抽样虽然很好,但不会买任何东西,因为据我所知抽样是可以的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM