5
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double ran_expo(lambda){
    double u;

    u = rand() / (RAND_MAX + 1.0);

    return -log(1- u) / lambda;
}

I am using this (I do not put other parts of the codes here) to generate random numbers of an exponential distribution lambda = 0.05. (Probability density function being lambda * exp(-lambda * x)).

However, I always get very small numbers, such as 0.000041, or something like 1.#INF00 (what is this?).

In fact, for exponential distribution with lambda = 0.05, numbers generated should be quite large, namely most are not far from 30. My results are very weird. In addition, the degree of precision is not satisfactory, only to 10^(-6). I tried long double, but it is still like this.

I am using DEV C++ under windows.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Damien
  • 43
  • 2
  • 7

2 Answers2

5

This is because you did not declare the type for lambda, having corrected that the results are in the range you seek. If undeclared, old compilers will assume it to be int.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

double ran_expo(double lambda){
    double u;
    u = rand() / (RAND_MAX + 1.0);
    return -log(1- u) / lambda;
}

int main(void)
{
    int i;
    srand((unsigned)time(NULL));
    for (i=0; i<20; i++)
        printf("%f\n", ran_expo(0.05));
    return 0;
}

Program output:

0.025040
16.582459
4.296027
33.079902
17.589123
13.073084
8.624299
45.254803
34.611211
27.454302
3.825699
39.168172
24.790600
14.411160
7.247698
0.301951
1.917010
9.065004
3.187146
3.627885
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Thanks, I was doubtful at first about your range of random numbers (concerned about `log(0)`) but I see you subtracted from `1`. – Weather Vane Jan 01 '16 at 17:42
  • There is a glaring fault in my answer. There is a difference between assuming that `int` is the default type, and declaring `int lambda`, but I don't know what it is. In the first case, every result is `-0.000000`. But with the explicit `int` type every result is `1.#INF00`, as you would expect, the result of div 0. (MSVC). – Weather Vane Jan 01 '16 at 18:06
0

I threw your code verbatim into code chef, it looks like it works fine. Compiler is gcc c++ 4.9.2 . This code prints out 36.6751:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>

using namespace std;

double ran_expo(double lambda){
    double u;

    u = rand() / (RAND_MAX + 1.0);

    return -log(1- u) / lambda;
}


int main() {
    cout << ran_expo(0.05);
    return 0;
}

Works the same way in C, too (again, gcc 4.9.2):

#include <stdlib.h>
#include <math.h>

double ran_expo(double lambda){
    double u;

    u = rand() / (RAND_MAX + 1.0);

    return -log(1- u) / lambda;
}


int main() {
    printf("%f\n", ran_expo(0.05));
    return 0;
}

Must be your compiler/libraries?

djhaskin987
  • 9,741
  • 4
  • 50
  • 86