P
porterboy76
Pieter Droogendijk wrote
There is a problem with this. A histogram will show a
non-uniform distribution of integers, if the range min:max
is a large proportion of RAND_MAX, or not a factor
of RAND_MAX. I use the following (by the way, I'm a newbie
C programmer; I think the algorithm is good even if the
code is not.)
/*
generate an array a of N random
integers drawn uniformly from the set
X = {x | amin <= x <= amax, x \in Z}
*/
#include <stdio.h>
#include <stdlib.h>
void rand_int_array(int a[], size_t N, int amin, int amax)
{
// argument checking ------------------------
if (amin>=amax)
{
printf("Improper use of function randint");
exit(EXIT_FAILURE);
}
// initialise --------------------------------
int nsection, lsection, uplim, i;
double x;
nsection = 1+amax-amin;
lsection = RAND_MAX/nsection;
uplim = lsection*nsection;
// random number generator -------------------
// seed rand() still to do...
// fill array
for (i=0;i<N;i++)
{
do
{
x = rand();
}
while (x>=uplim);
a = amin+(int) (x/lsection);
}
}
Maybe someone could suggest a good way to
seed rand() I am still reading up about this.
Date: Mon, Aug 18 2003 2:17 pm
Groups: comp.lang.c
I usually use a function like this:
min+(int) ((double)((max+1)-min)*rand()/(RAND_MAX+1.0))
to get a random integer between min and max. I've seen
that it's 'random enough' for my taste. No performance
beast though...
There is a problem with this. A histogram will show a
non-uniform distribution of integers, if the range min:max
is a large proportion of RAND_MAX, or not a factor
of RAND_MAX. I use the following (by the way, I'm a newbie
C programmer; I think the algorithm is good even if the
code is not.)
/*
generate an array a of N random
integers drawn uniformly from the set
X = {x | amin <= x <= amax, x \in Z}
*/
#include <stdio.h>
#include <stdlib.h>
void rand_int_array(int a[], size_t N, int amin, int amax)
{
// argument checking ------------------------
if (amin>=amax)
{
printf("Improper use of function randint");
exit(EXIT_FAILURE);
}
// initialise --------------------------------
int nsection, lsection, uplim, i;
double x;
nsection = 1+amax-amin;
lsection = RAND_MAX/nsection;
uplim = lsection*nsection;
// random number generator -------------------
// seed rand() still to do...
// fill array
for (i=0;i<N;i++)
{
do
{
x = rand();
}
while (x>=uplim);
a = amin+(int) (x/lsection);
}
}
Maybe someone could suggest a good way to
seed rand() I am still reading up about this.