Hey all,
How do I generate random numbers with Uniform distribution Uniform(a,b)
using C-programming? I want to generate uniform random numbers which
have mean following Uniform(p,q) and also variance as Uniform(s,t)? any
suggestion would be really appreciated.
The most straight-forward way is:
double uniform(double a, double b)
{
return rand() / (RAND_MAX + 1.0) * (b - a) + a;
}
This will return at most RAND_MAX different values equally spaced in the
range [a .. b).
If you need finer-grained numbers, such as the possibility to generate
each individual floating-point representation between the given values
with equal probability, you need a more sophisticated function.
The following function should achieve that, but it'll be slow if a and b
are close in magnitude.
double fp_uniform(double a, double b)
{
double t;
unsigned char *p = (unsigned char *)&t;
size_t i, n = 0;
do
{
for(i = 0; i < sizeof (double); i++)
{
p
= rand() / (RAND_MAX + 1.0) * (UCHAR_MAX + 1.0);
}
n++;
}
while(t == 0 || isnan(t) || t < a || t > b);
return t;
}
Note of that uniformly distributed floating-point numbers are a
completely different distribution to uniformly-distributed real numbers.
The floating-point numbers are highly skewed because of the exponent
and mantissa format.
For example, generating uniformly-distributed floating-point numbers
from 1 to 1048576, you will find the mean is around 78500, not around
524000 as one might expect.