Add DiceBag and tests

closes #7
This commit is contained in:
Austen McDonald
2016-04-15 23:09:39 -07:00
parent 8b6b60a31a
commit a1196c2ec3
2 changed files with 66 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace LotGD\Core;
class DiceBag {
public function chance(float $p): bool {
$r = $this->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;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace LotGD\Core\Tests;
use LotGD\Core\DiceBag;
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
class DiceBagTests extends \PHPUnit_Framework_TestCase {
public function testUniform() {
$db = new DiceBag();
$value = $db->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.));
}
}