Random numbers
Random numbers
// An example showing how to generate random floating
// point numbers between 0 and 1.
// Michael Ashley / UNSW / 02-Apr-2003
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(void) {
struct timeval t;
int i;
// Obtain the time of day, to microsecond resolution.
assert(0 == gettimeofday(&t, NULL));
printf("The time is %ld.%06ld seconds since the Unix epoch\n",
t.tv_sec, t.tv_usec);
// Use the number of microseconds as the seed for the system
// random number generator.
srandom(t.tv_usec);
// Generate and print ten random integers between 0 and RAND_MAX.
for (i = 0; i < 10; i++) {
printf("%ld\n", random());
}
// Generate and print ten random numbers between 0 and 1.0.
for (i = 0; i < 10; i++) {
printf("%.15f\n", random()/((double) RAND_MAX));
}
return 0;
}