calgorithmmathrandomexponential-distribution

Creating random number using Exponential distribution in a specified range?


I need to create random numbers in a user specified range. I understood how to create random numbers and refering to Generating random numbers of exponential distribution that question. However, I need my random numbers to be in a range. I wrote a piece of code, althogh it works in theory, because it calculates very little numbers it approaches 0 and give wrong numbers. My code is

        double u;
        double p1 =  -1.0 *  lambda * minvalue;
        double p2 =  -1.0 *  lambda * maxvalue;
        double a_min =  1 - exp(p1);
        double a_max =  1 - exp(p2);
        u = (rand() / (RAND_MAX + 1.0));
        double diff = a_min - a_max;
        u = u * (a_min - a_max);
        u = u + a_max;
        double p3 = 1.0- u;
        int x = (int)(-log(p3) / lambda);
        return x;

lambda, minvalue and maxvalue are all integers. How can I deal with this issue ot is there any alternative solutions?

My code deals with very little numbers and so it is rounded to 0 then the result is calculated wrongly .


Solution

  • Would you please try the following:

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    /*
     * note: lambda should be a positive number
     *       min and max should be non-negative and min < max
     */
    double rand_exp(int lambda, int min, int max)
    {   
        double u_min = exp(-min * lambda);
        double u_max = exp(-max * lambda);
    
        double u = u_min + (1.0 - rand() / (RAND_MAX + 1.0)) * (u_max - u_min);
        return -log(u) / lambda;
    }