From a1196c2ec3ae297704fc382453fb4c67c5e8f9b7 Mon Sep 17 00:00:00 2001 From: Austen McDonald Date: Fri, 15 Apr 2016 23:09:39 -0700 Subject: [PATCH] Add DiceBag and tests closes #7 --- src/DiceBag.php | 34 ++++++++++++++++++++++++++++++++++ tests/DiceBagTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 src/DiceBag.php create mode 100644 tests/DiceBagTest.php diff --git a/src/DiceBag.php b/src/DiceBag.php new file mode 100644 index 0000000..70ce8a5 --- /dev/null +++ b/src/DiceBag.php @@ -0,0 +1,34 @@ +uniform(0., 1.); + return $r < $p; + } + + public function uniform(float $min, float $max): float { + return (mt_rand(0, 100) / 100.0) * ($max - $min) + $min; + } + + public function normal(float $min, float $max): float { + if ($min > $max) { + $tmp = $max; + $max = $min; + $min = $tmp; + } else if ($min == $max) { + return $min; + } + + $mean = ($max - $min) / 2; + $r = 0; + do { + $u1 = mt_rand() / mt_getrandmax(); + $u2 = mt_rand() / mt_getrandmax(); + $r = sqrt(-2 * log($u1)) * cos(2 * pi() * $u2) + $mean; + } while ($r < $min || $r > $max); + return $r; + } +} diff --git a/tests/DiceBagTest.php b/tests/DiceBagTest.php new file mode 100644 index 0000000..3616738 --- /dev/null +++ b/tests/DiceBagTest.php @@ -0,0 +1,32 @@ +uniform(0., 1.); + $this->assertGreaterThan(0, $value); + $this->assertLessThan(1, $value); + } + + public function testNormal() { + $db = new DiceBag(); + $value = $db->normal(0., 1.); + $this->assertGreaterThan(0, $value); + $this->assertLessThan(1, $value); + + $value = $db->normal(1., 0.); + $this->assertGreaterThan(0, $value); + $this->assertLessThan(1, $value); + + $this->assertEquals(0, $db->normal(0., 0.)); + } +}