#include #include const unsigned int MY_RAND_MAX = ~0; /* 2 ^ sizeof(unsigned int) - 1 */ const unsigned int HOW_MANY = 1000000; const char *FILE_NAME = "out.rnd"; /* Last updated: Thu Aug 4 2005 This code was written to show how to extract pseudo-random numbers in the range [0, 1) from a random file. Each number will require sizeof(unsigned int) bytes from the file. Should I use just 2 bytes instead? I guess I should. The last version should be here: http://www.geocities.com/arhuaco/log/src/file2prng.c It computes the average of 1000000 (HOW_MANY) numbers. The mean should be close to 1/2 in a random sequence. You can generate such pseudo-random file with the program rng1.c. You can download the source of this generator from: http://www.geocities.com/arhuaco/log/src/rng1.c Compile with: $ gcc file2prng.c -O2 -o file2prng Complete usage example: $ wget http://www.geocities.com/arhuaco/log/src/rng1.c $ gcc rng1.c -o rng1 $ ./rng1 172245973 $ gcc file2prng.c -O2 -o file2prng $ ./file2prng average is 0.499691 TODO: Build a generator that uses a cellular atomaton in memory. This is the right way to do it. */ long double pseudo_random (FILE *); int main(int argc, char *argv[]) { FILE *p; int i; long double sum; p = fopen(FILE_NAME, "rb"); if (!p) { fprintf(stderr, "I could not open file %s\n", FILE_NAME); exit(EXIT_FAILURE); } sum = 0.0L; for (i = 0; i < HOW_MANY; ++i) { long double number; number = pseudo_random(p); /* printf ("%.10Lg\n", number); */ sum += number; } printf("average is %Lg\n", sum / HOW_MANY); fclose(p); return EXIT_SUCCESS; } long double pseudo_random (FILE *p) { unsigned int number; int actually_read; actually_read = fread(&number, sizeof(unsigned int), 1, p); if (actually_read != 1) { fprintf(stderr, "I coul'd read %d bytes from the stream. Sorry.\n", sizeof(unsigned int)); exit(EXIT_FAILURE); } if (number == MY_RAND_MAX) /* Should I use less bits? Perhaps 16? */ number --; return (long double)number / (long double)MY_RAND_MAX; }