Created
June 11, 2012 12:53
-
-
Save thijzert/2909955 to your computer and use it in GitHub Desktop.
Statistical simulations in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class St | |
{ | |
/** | |
* Generate a random number in the interval (0,1). | |
* | |
* Using the parameters $closed_left and/or $closed_right, the interval may | |
* be closed to [0,1), (0,1], or [0,1]. | |
**/ | |
public static function uniform( $closed_left = false, $closed_right = false ) | |
{ | |
// A large prime for the denominator | |
$D = 17638261; | |
$l = $closed_left ? 0 : 1; | |
$r = $closed_right ? $D : $D-1; | |
return mt_rand( $l, $r ) / $D; | |
} | |
/** | |
* Generate a random variable with a Gauss distribution | |
**/ | |
public static function normal( $mu = 0, $sigma = 1 ) | |
{ | |
if ( count(self::$_norm_buffer) == 0 ) | |
self::_fill_norm_buffer(); | |
return ( $sigma * array_shift(self::$_norm_buffer) ) + $mu; | |
} | |
private static $_norm_buffer = array(); | |
/** | |
* Generate two random variables with standard Gauss distribution, using | |
* the Box-Muller method. | |
**/ | |
private static function _fill_norm_buffer() | |
{ | |
$U = self::uniform(); | |
$V = self::uniform(); | |
self::$_norm_buffer[] = sqrt(-2*log($U)) * cos(2*M_PI*$V); | |
self::$_norm_buffer[] = sqrt(-2*log($U)) * sin(2*M_PI*$V); | |
} | |
/** | |
* Generate a random variable with an exponential distribution, | |
* with mean ( 1/$lambda ). | |
**/ | |
public static function exponential( $lambda = 1 ) | |
{ | |
return ( -1*log(self::uniform()) ) / $lambda; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment