RAND_MAX broken

Andrey Chernov ache at freebsd.org
Tue Jul 2 20:17:53 UTC 2013


On 02.07.2013 20:33, Bruce Evans wrote:
> I checked the values returned by rand().  The ACM part works as
> intended, so it never returns RAND_MAX.  It also never returns 0.  So
> the distribution of values in the documented range [0, RAND_MAX] is
> very non-uniform.  It is uniform in [1, RAND_MAX - 1].  To use this
> algorithm for rand(), 1 should have been subtracted, giving a range
> of [0, 0x7ffffffe].

Do you mean [0, 0x7ffffffd] (assuming 1 subtracted)?
See attached patch.
I don't see compatibility problems at least from POSIX specs point of
view - they don't say something specific about RAND_MAX.

-- 
http://ache.vniz.net/
bitcoin:13fGiNutKNHcVSsgtGQ7bQ5kgUKgEQHn7N
-------------- next part --------------
--- stdlib.h.bak	2013-07-03 00:08:25.000000000 +0400
+++ stdlib.h	2013-07-03 00:10:17.000000000 +0400
@@ -69,7 +69,7 @@
 #define	EXIT_FAILURE	1
 #define	EXIT_SUCCESS	0
 
-#define	RAND_MAX	0x7fffffff
+#define	RAND_MAX	0x7ffffffd
 
 __BEGIN_DECLS
 #ifdef _XLOCALE_H_
--- rand.c.bak	2013-07-03 00:08:00.000000000 +0400
+++ rand.c	2013-07-03 00:11:33.000000000 +0400
@@ -75,7 +75,8 @@
 	x = 16807 * lo - 2836 * hi;
 	if (x < 0)
 		x += 0x7fffffff;
-	return ((*ctx = x) % ((u_long)RAND_MAX + 1));
+	*ctx = x;
+	return (x - 1);
 #endif  /* !USE_WEAK_SEEDING */
 }
 


More information about the svn-src-head mailing list