0

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.

Community
  • 1
  • 1
Domenico
  • 19
  • 1
  • 5
  • 1
    You need to call srand with the time or something, to get some different numbers each run. – Neil Kirk Mar 24 '15 at 23:11
  • change line to `x = ((double) rand() / (RAND_MAX));` to `random = ((double) rand() / (RAND_MAX));` – Severin Pappadeux Mar 24 '15 at 23:16
  • The output of `rand()` is never actually used in the example code. It is clobbered a few lines down. Thus the fact that the random seed is not initialized is not where the problem lies, and makes this question not exactly a duplicate of questions relating to the use of `rand()`. – Randall Cook Mar 24 '15 at 23:17
  • And you could remove `one-`, U(0,1) is equivalent to 1-U(0,1) – Severin Pappadeux Mar 24 '15 at 23:17
  • You wouldn't have needed to write code; C++ has a built-in exponential distribution: http://stackoverflow.com/questions/11491458/how-to-generate-random-numbers-with-exponential-distribution-with-mean – MSalters Mar 25 '15 at 09:33

1 Answers1

2

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.

Randall Cook
  • 6,728
  • 6
  • 33
  • 68
  • oh! I missed it. thks – Domenico Mar 24 '15 at 23:16
  • @Domenico: Please note that your compiler should have told you "reading from uninitialized variable `random`". Make sure that your warnings are turned on, and then pay attention to them. – Ben Voigt Mar 25 '15 at 00:20