Skip to content
This repository has been archived by the owner on Jan 8, 2020. It is now read-only.

Commit

Permalink
Merge pull request #2 from ezimuel/feature/rand-refactor
Browse files Browse the repository at this point in the history
Proposed a new float random number generator
  • Loading branch information
denixport committed Jul 24, 2012
2 parents b4c538a + 5b83afe commit 8337359
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions library/Zend/Math/Rand.php
Expand Up @@ -116,22 +116,20 @@ public static function getInteger($min, $max, $strong = false)
*
* PHP uses double precision floating-point format (64-bit) which has
* 52-bits of significand precision. We gather 7 bytes of random data,
* clear last 4 bits, then add 8th NULl byte
* and we fix the exponent to the bias (1023). In this way we generate
* a float of 1.mantissa.
*
* @param boolean $strong true if you need a strong random generator (cryptography)
* @return float
*/
public static function getFloat($strong = false)
{
$bytes = static::getBytes(7, $strong);
$bytes[6] = $bytes[6] & chr(0x0F); // clear last 4 bits
$bytes .= chr(0);

// unpack two unsigned long (32-bit)
list(, $a, $b) = unpack('V2', $bytes);

// The second unsigned long has 20-bits of significant precision
return (float) ($a / pow(2.0, 52) + $b / pow(2.0, 20));
$bytes[6] = $bytes[6] | chr(0xF0);
$bytes .= chr(63); // exponent bias (1023)
list(, $float) = unpack('d', $bytes);

return $float - 1;
}

/**
Expand Down

0 comments on commit 8337359

Please sign in to comment.