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)
commit2b2f76287a982b4dbd20892749fc76649107ea36
treec66e48d32a72b74a09513ad078e356d89d887cb3
parent93dfa11d80549b540e8a160c52542b26dc7f05dd
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
includes/GlobalFunctions.php