2 * m_rand -- provides pseudorandom bytes
4 * This code is Copyright (c) 2012, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
9 #include <stdlib.h> /* for abs(), srand(), rand() */
10 #include <stdio.h> /* for fopen(), fread(), fclose() */
11 #include <unistd.h> /* for getpid() */
12 #include <time.h> /* for time() */
14 static int seeded = 0;
18 m_rand (unsigned char *buf, size_t n) {
23 if ((devurandom = fopen ("/dev/urandom", "r"))) {
24 if (fread (&seed, sizeof (seed), 1, devurandom) == 1) seeded = 1;
29 /* This seed calculation is from Helmut G. Katzgraber, "Random
30 Numbers in Scientific Computing: An Introduction",
31 arXiv:1005.4117v1 [physics.comp-ph], 22 May 2010, p. 19.
32 time() and getpid() shouldn't fail on POSIX platforms. */
33 seed = abs ((int) ((time (0) * 181 * ((getpid ()-83) * 359)) % 104729));
42 unsigned char *rndp = (unsigned char *) &rnd;
45 for (i = 0; i < sizeof rnd && n > 0; ++i, --n) {