生成属于指数分布的随机数

Generate random number belonging to exponential distribution

我正在尝试生成属于指数分布的随机值。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <math.h>

using namespace std;

int main(){
    double x;
    double random;
    double one=1.0;
    for(int i=0; i<1000; i++){
        x = ((double) rand() / (RAND_MAX));
        cout << random <<endl;
        x=log(one-random)/(-3);
        cout<< x<< endl;
        cout<< "__"<<endl;
    }
    return 0;
}

我正在使用我在这篇 post Pseudorandom Number Generator - Exponential Distribution

中读到的这个公式 x = log(1-u)/(−λ)

但我看到的输出是这个:

3.90272e-319
0
__
3.90272e-319
0
__
3.90272e-319
0
__
3.90272e-319
0
__
and so on

总是打印相同的随机数值,而且对数的结果总是0,我看不懂。

您使用的 random 未初始化,因此未定义它将持有什么值。而且你永远不会改变它的值,所以循环的每次迭代都会表现相同。