Doc: result domain for GlobalFunctions::wfRandom()
authorStephen Niedzielski <stephen@niedzielski.com>
Thu, 25 Oct 2018 13:30:25 +0000 (07:30 -0600)
committerNiedzielski <sniedzielski@wikimedia.org>
Mon, 12 Nov 2018 02:07:30 +0000 (02:07 +0000)
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

includes/GlobalFunctions.php

index 6e95871..009c953 100644 (file)
@@ -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.
  *