From: Stephen Niedzielski Date: Thu, 25 Oct 2018 13:30:25 +0000 (-0600) Subject: Doc: result domain for GlobalFunctions::wfRandom() X-Git-Tag: 1.34.0-rc.0~3498^2 X-Git-Url: http://git.cyclocoop.org/%28?a=commitdiff_plain;h=2b2f76287a982b4dbd20892749fc76649107ea36;p=lhc%2Fweb%2Fwiklou.git Doc: result domain for GlobalFunctions::wfRandom() Domain is an important property to document for callers. For example, random numbers are often used in calculations that are input into array index calculations and the knowledge that a function can or cannot ever return the integer 1 helps avoid rare off-by-one errors that may occur. `int( wfRandom() * count( $array ) )` will always yield an in-bounds index if wfRandom() returns [0, 1) but can make no such guarantee for [0, 1]. It's not immediately obvious from the implementation whether the endpoints of the domain of wfRandom() are inclusive or exclusive. This patch calculates the minimum and maximum results and documents it. For its minimal value, given `mt_getrandmax()` returns 1 and `mt_rand()` returns 0: $max = mt_getrandmax() + 1; $max = 2; $rand = ( mt_rand() * $max + mt_rand() ) / $max / $max; $rand = ( 0 * 2 + 0 ) / 2 / 2; $rand = 0; For its maximal value, given `mt_getrandmax()` returns 2^31 - 1 and `mt_rand()` also returns 2^31 - 1. $max = mt_getrandmax() + 1; $max = 2^31 - 1 + 1; $max = 2^31; $rand = ( mt_rand() * $max + mt_rand() ) / $max / $max; $rand = ( (2^31 - 1) * 2^31 + 2^31 - 1 ) / 2^31 / 2^31; $rand = ( 2^62 - 2^31 + 2^31 - 1 ) / 2^31 / 2^31; $rand = 2^62 / 2^62 - 1 / 2^62; $rand = 1 - 2^-62; // Less than 1. Change-Id: Ib179d70902e231eaeeafe6449f505464eb25204d --- diff --git a/includes/GlobalFunctions.php b/includes/GlobalFunctions.php index 6e95871885..009c953e15 100644 --- a/includes/GlobalFunctions.php +++ b/includes/GlobalFunctions.php @@ -266,7 +266,7 @@ function wfObjectToArray( $objOrArray, $recursive = true ) { } /** - * Get a random decimal value between 0 and 1, in a way + * Get a random decimal value in the domain of [0, 1), in a way * not likely to give duplicate values for any realistic * number of articles. *