2

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 .

mobiusT
  • 47
  • 4
  • Does [this](https://stackoverflow.com/a/19307882/2166798) address your question? It shows how to create an upper bound, but the same logic can be used to create a lower bound as well. – pjs Mar 23 '22 at 20:04
  • mobiusT, Post some sample values of `lambda, minvalue, maxvalue`. Also what are the min/max of those 3 for your application? Any other limitations like `minvalue < maxvalue`? – chux - Reinstate Monica Mar 23 '22 at 21:54

1 Answers1

0

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;
}
  • Please note the function does not check the illegal parameters.
  • I have defined the function to return the double value because it is easier to test the output. Please cast it to int based on your requirement.
tshiono
  • 21,248
  • 2
  • 14
  • 22