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 .
Aucun commentaire:
Enregistrer un commentaire