summaryrefslogtreecommitdiff
path: root/ext/standard/php_rand.h
diff options
context:
space:
mode:
authorLeigh <leigh@php.net>2016-07-05 11:16:37 +0100
committerLeigh <leigh@php.net>2016-07-05 11:16:37 +0100
commiteba6e7ce9ac721b072ee3afb1cae883b774f3714 (patch)
tree64d15dbc8a2cc837e2722b9ed3d36da2ce1dfc8a /ext/standard/php_rand.h
parent421cc65510cead9c554f87e83edd0f903a733969 (diff)
downloadphp-git-eba6e7ce9ac721b072ee3afb1cae883b774f3714.tar.gz
Split rand and mt_rand into separate files
Diffstat (limited to 'ext/standard/php_rand.h')
-rw-r--r--ext/standard/php_rand.h32
1 files changed, 25 insertions, 7 deletions
diff --git a/ext/standard/php_rand.h b/ext/standard/php_rand.h
index 39ba00eb56..b145440d71 100644
--- a/ext/standard/php_rand.h
+++ b/ext/standard/php_rand.h
@@ -25,8 +25,6 @@
#ifndef PHP_RAND_H
#define PHP_RAND_H
-#include <stdlib.h>
-#include "basic_functions.h"
#include "php_lcg.h"
/* System Rand functions */
@@ -41,12 +39,34 @@
#define PHP_RAND_MAX RAND_MAX
#endif
+/*
+ * A bit of tricky math here. We want to avoid using a modulus because
+ * that simply tosses the high-order bits and might skew the distribution
+ * of random values over the range. Instead we map the range directly.
+ *
+ * We need to map the range from 0...M evenly to the range a...b
+ * Let n = the random number and n' = the mapped random number
+ *
+ * Then we have: n' = a + n(b-a)/M
+ *
+ * We have a problem here in that only n==M will get mapped to b which
+ # means the chances of getting b is much much less than getting any of
+ # the other values in the range. We can fix this by increasing our range
+ # artificially and using:
+ #
+ # n' = a + n(b-a+1)/M
+ *
+ # Now we only have a problem if n==M which would cause us to produce a
+ # number of b+1 which would be bad. So we bump M up by one to make sure
+ # this will never happen, and the final algorithm looks like this:
+ #
+ # n' = a + n(b-a+1)/(M+1)
+ *
+ * -RL
+ */
#define RAND_RANGE(__n, __min, __max, __tmax) \
(__n) = (__min) + (zend_long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))
-/* MT Rand */
-#define PHP_MT_RAND_MAX ((zend_long) (0x7FFFFFFF)) /* (1<<31) - 1 */
-
#ifdef PHP_WIN32
#define GENERATE_SEED() (((zend_long) (time(0) * GetCurrentProcessId())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))
#else
@@ -55,7 +75,5 @@
PHPAPI void php_srand(zend_long seed);
PHPAPI zend_long php_rand(void);
-PHPAPI void php_mt_srand(uint32_t seed);
-PHPAPI uint32_t php_mt_rand(void);
#endif /* PHP_RAND_H */