F
frank
Ben said:i = (int) ((double) rand () / ((double) RAND_MAX + 1) * N);
Here be dragons. As 64 bit integers get more and more common we are
edging towards a time when this will routinely fail because
(double)RAND_MAX + 1 can be equal to RAND_MAX if RAND_MAX is big
enough. This does not happen with a 32 RNG and normal IEEE
double-precision numbers, but if RAND_MAX is big enough (and a signed
64-bit int is big enough) the +1 has no effect on (double)RAND_MAX.
To get a floating-point number in [0, 1) I have taken to writing:
nextafter((double)rand() / RAND_MAX, 0)
nextafter is a C99 function that gives the next representable number,
near the first argument in the direction of the second. There are
probably better ways to do this, but the best of all would be a
floating-point random function in C. Such a function could rely on
the internal representation of a floating point number to give a
properly uniform distribution. Many C libraries include such a
function as an extension.
Is gcc one of them?
dan@dan-desktop:~/source$ gcc -std=c99 -Wall -Wextra mort3.c -o out; ./out
mort3.c: In function ‘main’:
mort3.c:12: warning: unused variable ‘c’
/tmp/ccAPcgbE.o: In function `main':
mort3.c
collect2: ld returned 1 exit status
bash: ./out: No such file or directory
dan@dan-desktop:~/source$ cat mort3.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define N 26
int
main (void)
{
int i;
char c;
srand(time(NULL));
printf ("RAND_MAX is %d\n", RAND_MAX);
i = nextafter((double)rand() / RAND_MAX, 0);
printf ("i is %d\n", i);
return 0;
}
// gcc -std=c99 -Wall -Wextra mort3.c -o out; ./out