summaryrefslogtreecommitdiffstats
path: root/lib/libc/stdlib
diff options
context:
space:
mode:
authorache <ache@FreeBSD.org>2001-02-27 14:42:19 +0000
committerache <ache@FreeBSD.org>2001-02-27 14:42:19 +0000
commit364634966741ad5baf75248af0993a235b9856f9 (patch)
tree3964ea732b5707442d1264551b69424fe13743f3 /lib/libc/stdlib
parent79916cd3d7729ab669caf75c17660121c1474845 (diff)
downloadFreeBSD-src-364634966741ad5baf75248af0993a235b9856f9.zip
FreeBSD-src-364634966741ad5baf75248af0993a235b9856f9.tar.gz
Use formula with better random distribution for rand()
Even better formula from random() could not be intetgrated because rand_r() supposed to store its state in the single variable (but table needed for random() algorithm integration).
Diffstat (limited to 'lib/libc/stdlib')
-rw-r--r--lib/libc/stdlib/rand.c26
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/libc/stdlib/rand.c b/lib/libc/stdlib/rand.c
index 94f6b50..70285bd 100644
--- a/lib/libc/stdlib/rand.c
+++ b/lib/libc/stdlib/rand.c
@@ -31,6 +31,8 @@
* SUCH DAMAGE.
*
* Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
+ *
+ * $FreeBSD$
*/
#if defined(LIBC_SCCS) && !defined(lint)
@@ -47,7 +49,31 @@ static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93";
static int
do_rand(unsigned long *ctx)
{
+#ifdef USE_WEAK_SEEDING
+/*
+ * Historic implementation compatibility.
+ * The random sequences do not vary much with the seed,
+ * even with overflowing.
+ */
return ((*ctx = *ctx * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
+#else /* !USE_WEAK_SEEDING */
+/*
+ * Compute x = (7^5 * x) mod (2^31 - 1)
+ * wihout overflowing 31 bits:
+ * (2^31 - 1) = 127773 * (7^5) + 2836
+ * From "Random number generators: good ones are hard to find",
+ * Park and Miller, Communications of the ACM, vol. 31, no. 10,
+ * October 1988, p. 1195.
+ */
+ long hi, lo, x;
+
+ hi = *ctx / 127773;
+ lo = *ctx % 127773;
+ x = 16807 * lo - 2836 * hi;
+ if (x <= 0)
+ x += 0x7fffffff;
+ return ((*ctx = x) % ((u_long)RAND_MAX + 1));
+#endif /* !USE_WEAK_SEEDING */
}
OpenPOWER on IntegriCloud