简体   繁体   中英

Generate random number belonging to exponential distribution

I'm trying to generate random values belonging to an 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;
}

I'm using this formula x = log(1-u)/(−λ) that I have read in this post Pseudorandom Number Generator - Exponential Distribution

But the output that I see is this one:

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

It is always printed the same value of the random number and also the result of the logarithm is always 0, I can't understand way.

You are using random uninitialized, so it is undefined what value it will hold. And you are never changing its value, so each iteration of the loop it will behave the same.

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.

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